home *** CD-ROM | disk | FTP | other *** search
/ C & C++ Multimedia Cyber Classroom / C and C++ Multimedia Cyber Classroom (Prentice Hall) (1998).iso / cpphtp2 / cpphtp2.jar / chpt_08.gml < prev    next >
Text File  |  1998-03-03  |  120KB  |  2,959 lines

  1. <html>
  2. <chapter>
  3. <section type=Popup name=Quotes title="Quotes">
  4. <page>
  5. <i>"The die is cast."</i>  <br>
  6. Julius Caesar<br>
  7. <br>
  8.  
  9. </page>
  10. <page>
  11. <i>"Our doctor would never 
  12. really operate unless it 
  13. was necessary. He was 
  14. just that way. If he didn't 
  15. need the money, he 
  16. wouldn't lay a hand on 
  17. you." </i>  <br>
  18. Herb Shriner<br>
  19. <br>
  20.  
  21. </page>
  22. <page>
  23. <i>"The whole difference 
  24. between construction and 
  25. creation is exactly this: 
  26. that a thing constructed 
  27. can only be loved after it 
  28. is constructed; but a thing 
  29. created is loved before it 
  30. exists." </i> <br>
  31.  
  32. </page>
  33. <page>
  34. Gilbert Keith Chesterton, 
  35. Preface to Dickens, 
  36. Pickwick Papers<br>
  37. <br>
  38.  
  39. </page>
  40. </section>
  41. <section type=Popup name=Answers title="Answers">
  42. <page pagename="Answer 8.1">
  43. <b>Answer 8.1</b><br>
  44. a) operator overloading.<br>
  45. b) <b>operator</b>.<br>
  46. c) assignment (<b>=</b>), address(<b>&</b>).<br>
  47. d) precedence, associativity, "arity."<br>
  48. <foreign  name="exercises" url="^Exercises::c:s0p0">
  49. <br>
  50.  
  51. </page>
  52. <page pagename="Answer 8.2">
  53. <b>Answer 8.2</b><br>
  54. Operator <b>>></b> is both the right-shift operator and the stream-extraction operator 
  55. depending on its context. Operator<b> <<</b> is both the left-shift operator and the 
  56. stream-insertion operator depending on its context.<br>
  57. <foreign  name="exercises" url="^Exercises::c:s0p1">
  58.  
  59. </page>
  60. <page pagename="Answer 8.3">
  61. <b>Answer 8.3</b><br>
  62. For operator overloading: It would be the name of a function that would provide 
  63. an overloaded version of the <b>/</b> operator. <br>
  64. <foreign  name="exercises" url="^Exercises::c:s0p2">
  65.  
  66. </page>
  67. <page pagename="Answer 8.4">
  68. <b>Answer 8.4</b><br>
  69. True.<br>
  70. <foreign  name="exercises" url="^Exercises::c:s0p3">
  71. <br>
  72.  
  73. </page>
  74. <page pagename="Answer 8.5">
  75. <b>Answer 8.5</b><br>
  76. Identical.<br>
  77. <foreign  name="exercises" url="^Exercises::c:s0p4">
  78.  
  79. </page>
  80. <page pagename="Answer 8.12 ">
  81. <b>Answer 8.12 </b><br>
  82. The solution to this exercise can be found on your Cyber Classroom CD. Copy 
  83. the file cpphtp2/answers/P8_12.zip to your hard drive and unzip the program 
  84. code. <br>
  85. <foreign  name="exercises" url="^Exercises::c:s0p11">
  86.  
  87. </page>
  88. <page pagename="Answer 8.15 ">
  89. <b>Answer 8.15 </b><br>
  90. The solution to this exercise can be found on your Cyber Classroom CD. Copy 
  91. the file cpphtp2/answers/P8_15.zip to your hard drive and unzip the program 
  92. code. <br>
  93. <foreign  name="exercises" url="^Exercises::c:s0p15">
  94.  
  95. </page>
  96. <page pagename="Answer 8.19 ">
  97. <b>Answer 8.19 </b><br>
  98. The solution to this exercise can be found on your Cyber Classroom CD. Copy 
  99. the file cpphtp2/answers/P8_19.zip to your hard drive and unzip the program 
  100. code. <br>
  101. <foreign  name="exercises" url="^Exercises::c:s0p19">
  102.  
  103. </page>
  104. </section>
  105. <section type=Body name=Default title="8 Operator Overloading">
  106. <page>
  107. <font size=18 bold>8 Operator Overloading</font><hr>
  108. <a href="#s1p0">8.1<spacer width=20 height=1>Introduction</a>  <br>
  109. <a href="#s2p0">8.2<spacer width=20 height=1>Fundamentals of Operator Overloading</a>  <br>
  110. <a href="#s3p0">8.3<spacer width=20 height=1>Restrictions on Operator Overloading</a>  <br>
  111. <a href="#s4p0">8.4<spacer width=20 height=1>Operator Functions as Class Members vs. as Friend 
  112. Functions</a>  <br>
  113. <a href="#s5p0">8.5<spacer width=20 height=1>Overloading Stream-Insertion and Stream-
  114. Extraction Operators</a>  <br>
  115. <a href="#s6p0">8.6<spacer width=20 height=1>Overloading Unary Operators</a>  <br>
  116. <a href="#s7p0">8.7<spacer width=20 height=1>Overloading Binary Operators</a>  <br>
  117. <foreign  name="objectivesButton" url="^Objective::c:s0p0">
  118. <foreign  name="quotes" url="^Quotes::c:s0p0">
  119.  
  120. </page>
  121. <page>
  122. <a href="#s8p0">8.8<spacer width=20 height=1>Case Study: An Array Class</a>  <br>
  123. <a href="#s9p0">8.9<spacer width=20 height=1>Converting Between Types</a>  <br>
  124. <a href="#s10p0">8.10<spacer width=20 height=1>Case Study: A String Class</a>  <br>
  125. <a href="#s11p0">8.11<spacer width=20 height=1>Overloading ++ and --</a>  <br>
  126. <a href="#s12p0">8.12<spacer width=20 height=1>Case Study: A Date Class</a>  <br>
  127. <a href="#s13p0">8.13<spacer width=20 height=1>Summary</a>  <br>
  128. <a href="^Terminology::c:s0p0">Terminology</a>  <br>
  129. <a href="^Illustration::c:s0p0">Figures</a>  <br>
  130. <foreign  name="objectivesButton" url="^Objective::c:s0p0">
  131. <foreign  name="quotes" url="^Quotes::c:s0p0">
  132.  
  133. </page>
  134. </section>
  135. <section type=Body name=Default title="8.1 Introduction">
  136. <page>
  137. <font size=18 bold>8.1 Introduction</font><hr>
  138. In Chapters 6 and 7 we introduced the basics of C++ 
  139. classes and the notion of abstract data types (ADTs). 
  140. Manipulations on class objects (i.e., instances of ADTs) 
  141. were accomplished by sending messages (in the form of 
  142. member function calls) to the objects. This function-
  143. call notation is cumbersome for certain kinds of classes, 
  144. especially mathematical classes. For these kinds of 
  145. classes it would be nice to use C++'s rich set of built-in 
  146. operators to specify object manipulations. In this 
  147. chapter, we show how to enable C++'s operators to 
  148. work with class objects. This process is called <i>operator</i> <br>
  149.  
  150. </page>
  151. <page>
  152. <i>overloading</i>. It is straightforward and natural to extend 
  153. C++ with these new capabilities. It also requires great 
  154. care because when overloading is misused it can make a 
  155. program difficult to understand.<br>
  156. <spacer width=16 height=1>Operator <b><<</b> has several purposes in C++--as the 
  157. stream-insertion operator and as the bitwise left-shift 
  158. operator. This is an example of operator overloading. 
  159. Similarly, <b>>></b> is also overloaded; it is used both as the 
  160. stream-extraction operator and as the bitwise right-shift 
  161. operator. Both of these operators are overloaded in the 
  162. C++ class library. The C++ language itself overloads <b>+</b> 
  163. and <b>-</b>. These operators perform differently depending <br>
  164.  
  165. </page>
  166. <page>
  167. on their context in integer arithmetic, floating-point 
  168. arithmetic, and pointer arithmetic.<br>
  169. <spacer width=16 height=1>C++ enables the programmer to overload most 
  170. operators to be sensitive to the context in which they 
  171. are used. The compiler generates the appropriate code 
  172. based on the manner in which the operator is used. 
  173. Some operators are overloaded frequently, especially 
  174. the assignment operator and various arithmetic 
  175. operators such as <b>+</b> and <b>-</b>. The job performed by 
  176. overloaded operators can also be performed by explicit 
  177. function calls, but operator notation is often clearer.<br>
  178. <spacer width=16 height=1>We will discuss when to use operator overloading and 
  179. when not to use operator overloading. We show how to <br>
  180.  
  181. </page>
  182. <page>
  183. overload operators, and we present many complete 
  184. programs using overloaded operators. <br>
  185.  
  186. </page>
  187. </section>
  188. <section type=Body name=Default title="8.2 Fundamentals of Operator Overloading">
  189. <page>
  190. <font size=18 bold>8.2 Fundamentals of Operator Overloading</font><hr>
  191. C++ programming is a type-sensitive and type-focused 
  192. process. Programmers can use built-in types and can 
  193. define new types. The built-in types can be used with 
  194. C++'s rich collection of operators. Operators provide 
  195. programmers with a concise notation for expressing 
  196. manipulations of objects of built-in types. <br>
  197. <spacer width=16 height=1>Programmers can use  <a href="^Engineer::c:s0p0"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>operators with user-defined types 
  198. as well. Although C++ does not allow new operators to 
  199. be created, it does allow most existing operators to be  
  200. <a href="^Practice::c:s0p1"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>overloaded so that when these operators are used with 
  201. class objects, the operators have meaning appropriate to <br>
  202.  
  203. </page>
  204. <page>
  205. the new types. This is one of C++'s most powerful 
  206. features. <br>
  207. <spacer width=16 height=1>Although  <a href="^Practice::c:s0p0"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>operator overloading may sound like an 
  208. exotic capability, most programmers implicitly use 
  209. overloaded operators regularly. For example, the 
  210. addition operator (<b>+</b>) operates quite differently on 
  211. integers, floats, and doubles. But addition nevertheless 
  212. works fine with variables of type <b>int,</b> <b>float</b>, <b>double</b>, and 
  213. a number of other built-in types because the addition 
  214. operator (<b>+</b>) has been overloaded in the C++ language 
  215. itself. <br>
  216. <spacer width=16 height=1>Operators are overloaded by writing a function 
  217. definition (with a header and body) as you normally <br>
  218.  
  219. </page>
  220. <page>
  221. would, except that the function name now becomes the 
  222. keyword <b>operator </b>followed by the symbol for the 
  223. operator being overloaded. For example, the function 
  224. name <b>operator+</b> would be used to overload the 
  225. addition operator (<b>+</b>).<br>
  226. <spacer width=16 height=1>To use an operator on class objects, that operator <i>must</i> 
  227. be overloaded--with two exceptions. The assignment 
  228. operator (<b>=</b>) may be used with every class without 
  229. explicit overloading. The default behavior of the 
  230. assignment operator is a <i>memberwise assignment </i>of the 
  231. data members of the class. We will soon see that such 
  232. default memberwise assignment is dangerous for 
  233. classes with pointer members; we will explicitly <br>
  234.  
  235. </page>
  236. <page>
  237. overload the assignment operator for such classes. The 
  238. address operator (<b>&</b>) may also be used with objects of 
  239. any class without overloading; it simply returns the 
  240. address of the object in memory. The address operator 
  241. can also be overloaded. <br>
  242. <spacer width=16 height=1>Overloading is most appropriate for mathematical 
  243. classes. These often require that a substantial set of 
  244. operators be overloaded to ensure consistency with the 
  245. way these mathematical classes are handled in the real 
  246. world. For example, it would be unusual to overload 
  247. only addition for a complex number class because other 
  248. arithmetic operators are also commonly used with 
  249. complex numbers.<br>
  250.  
  251. </page>
  252. <page>
  253. C++ is an operator-rich language. C++ programmers 
  254. who understand the meaning and context of each 
  255. operator are likely to make reasonable choices when it 
  256. comes to overloading operators for new classes.<br>
  257. <spacer width=16 height=1>The point of operator overloading is to provide the 
  258. same concise expressions for user-defined types that 
  259. C++ provides with its rich collection of  <a href="^Practice::c:s0p3"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>operators for 
  260. built-in types. Operator overloading is not automatic, 
  261. however; the programmer must write operator 
  262. overloading functions to perform the desired 
  263. operations. Sometimes these functions are best made 
  264. member functions; sometimes they are best as <tt><b>friend</b></tt> <br>
  265.  
  266. </page>
  267. <page>
  268. functions; and occasionally they can be made non-
  269. member, non-<b>friend</b> functions.<br>
  270. <spacer width=16 height=1>Extreme misuses of overloading are possible such as 
  271. overloading operator <b>+</b> to perform subtraction-like 
  272. operations or overloading  <a href="^Practice::c:s0p2"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>operator <b>/</b> to perform 
  273. multiplication-like operations. Such uses of 
  274. overloading make a program extremely difficult to 
  275. comprehend.<br>
  276.  
  277. </page>
  278. <page>
  279. <b>Select the true statement(s). </b><br>
  280. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  281. C++ allows operators to be overloaded. <br>
  282. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. Operators cannot be created in C++.">
  283. C++ allows new operators to be created.   <br>
  284. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. Some operators cannot be overloaded.">
  285. Any operator can be overloaded. <br>
  286. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  287. The operator keyword is used when defining new operators. <br>
  288. <component type=button name=b label="Check Your Answer" width=125 height=24>
  289.  
  290. </page>
  291. </section>
  292. <section type=Body name=Default title="8.3 Restrictions on Operator Overloading">
  293. <page>
  294. <font size=18 bold>8.3 Restrictions on Operator Overloading</font><hr>
  295. Most of C++'s operators can be overloaded. These are 
  296. shown in <a href="^Illustration::c:s0p1"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 8.1</a>. <a href="^Illustration::c:s0p2"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Figure 8.2</a> shows the operators that 
  297. cannot be overloaded.<br>
  298. <spacer width=16 height=1>The precedence of an  <a href="^Errors::c:s0p0"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>operator cannot be changed by 
  299. overloading. This can lead to awkward situations in 
  300. which an operator is overloaded in a manner for which 
  301. its fixed precedence is inappropriate. However, 
  302. parentheses can be used to force the order of evaluation 
  303. of overloaded operators in an expression.  <br>
  304. The associativity of an operator cannot be changed by 
  305. overloading. <br>
  306.  
  307. </page>
  308. <page>
  309. It is not possible to change the "arity" of an operator 
  310. (i.e., the number of operands an operator takes): 
  311. Overloaded unary operators remain as unary operators; 
  312. overloaded binary operators remain as binary operators. 
  313. C++'s only ternary operator (<b>?:</b>) cannot be overloaded 
  314. (<a href="^Illustration::c:s0p2"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Fig. 8.2</a>). Operators <b>&</b>, <b>*</b>, <b>+</b> and <b>-</b> each have unary and 
  315. binary versions; these unary and binary versions can be 
  316. overloaded separately.<br>
  317. <spacer width=16 height=1>It is not possible to create new  <a href="^Errors::c:s0p1"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>operators; only existing 
  318. operators can be overloaded. Unfortunately, this 
  319. prevents the programmer from using popular notations 
  320. like the <b>**</b> operator used in BASIC for exponentiation <br>
  321.  
  322. </page>
  323. <page>
  324. The meaning of how an operator works on objects of 
  325. built-in types cannot be changed by operator 
  326. overloading. The programmer cannot, for example, 
  327. change the meaning of how <b>+</b> adds two integers.  
  328. <a href="^Practice::c:s0p4"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>Operator  <a href="^Errors::c:s0p2"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>overloading works only with objects of user-
  329. defined types or with a mixture of an  <a href="^Engineer::c:s0p1"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>object of a user-
  330. defined type and an object of a  <a href="^Errors::c:s0p5"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>built-in type. <br>
  331. <spacer width=16 height=1>Overloading an assignment  <a href="^Errors::c:s0p3"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>operator and an addition 
  332. operator to allow statements like<br>
  333. <font size=2><br></font><font size=11><pre>
  334. object2 = object2 + object1;<p>
  335. </pre></font>
  336. does not imply that the <b>+=</b> operator is also overloaded 
  337. to allow statements such as<br>
  338. <font size=2><br></font><font size=11><pre>
  339. object2 += object1;<p>
  340. </pre></font>
  341.  
  342. </page>
  343. <page>
  344. Such behavior can be achieved by explicitly 
  345. overloading the <b>+=</b> operator for that class.<br>
  346.  
  347. </page>
  348. <page>
  349. <b>Select the true statement(s). </b><br>
  350. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  351. How an operator works on fundamental types cannot be changed by operator overloading.  <br>
  352. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. Operator overloading cannot change the associativity of an operator.">
  353. The associativity of an operator can be changed by operator overloading.   <br>
  354. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  355. The precedence of an operator cannot be changed by overloading. <br>
  356. <component type=button name=b label="Check Your Answer" width=125 height=24>
  357.  
  358. </page>
  359. </section>
  360. <section type=Body name=Default title="8.4 Operator Functions as Class Members vs. as Friend Functions">
  361. <page>
  362. <font size=18 bold>8.4 Operator Functions as Class Members 
  363. vs. as Friend Functions</font><hr>
  364. Operator functions can be member functions or non-
  365. member functions; non-member functions are often 
  366. made <tt><b>friends</b></tt> for performance reasons. The member 
  367. functions use the <b>this</b> pointer implicitly to obtain one of 
  368. their class object arguments. That class argument must 
  369. be explicitly listed in a non-member function call.<br>
  370. <spacer width=16 height=1>When overloading <b>()</b>, <b>[]</b>, <b>-></b>, or any of the assignment 
  371. operators, the operator overloading function must be 
  372. declared as a class member. For the other operators, the <br>
  373.  
  374. </page>
  375. <page>
  376. operator overloading functions can be non-member 
  377. functions. <br>
  378. <spacer width=16 height=1>Whether an operator function is implemented as a 
  379. member function or as a non-member function, the 
  380. operator is still used the same way in expressions. So 
  381. which implementation is best? <br>
  382. <spacer width=16 height=1>When an operator function is implemented as a member 
  383. function, the leftmost (or only) operand must be a class 
  384. object (or a reference to a class object) of the operator's 
  385. class. If the left operand must be an object of a different 
  386. class or a built-in type, this operator function must be 
  387. implemented as a non-member function (as we will do 
  388. in<a href="#s5p0"> Section 8.5</a> when overloading <b><<</b> and <b>>></b> as the <br>
  389.  
  390. </page>
  391. <page>
  392. stream-insertion and stream-extraction operators, 
  393. respectively). A non-member operator function needs 
  394. to be a <b>friend</b> if that function must access <b>private</b> or 
  395. <b>protected</b> members of that class directly.<br>
  396. <spacer width=16 height=1>The overloaded <b><<</b> operator must have a left operand of 
  397. type <b>ostream &</b> (such as <b>cout</b> in the expression <b>cout 
  398. << classObject</b>), so it must be a non-member function. 
  399. Similarly, the overloaded <b>>></b> operator must have a left 
  400. operand of type <b>istream &</b> (such as <b>cin</b> in the 
  401. expression <b>cin >> classObject</b>), so it, too, must be a 
  402. non-member function. Also, each of these overloaded 
  403. operator functions may require access to the <b>private</b> 
  404. data members of the class object being output or input, <br>
  405.  
  406. </page>
  407. <page>
  408. so these overloaded operator functions are sometimes 
  409. made <b>friend</b>  <a href="^Perform::c:s0p0"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>functions of the class for performance 
  410. reasons.<br>
  411. <spacer width=16 height=1>Operator member functions of a specific class are called 
  412. only when the left operand of a binary operator is 
  413. specifically an object of that class, or when the single 
  414. operand of a unary operator is an object of that class.<br>
  415. <spacer width=16 height=1>Another reason why one might choose a non-member 
  416. function to overload an operator is to enable the 
  417. operator to be commutative. For example, suppose we 
  418. have an object, <b>number</b>, of type <b>long int</b>, and an object 
  419. <b>bigInteger1</b>, of class <b>HugeInteger</b> (a class in which 
  420. integers may be arbitrarily large rather than being <br>
  421.  
  422. </page>
  423. <page>
  424. limited by the machine word size of the underlying 
  425. hardware; class <b>HugeInteger</b> is developed in the 
  426. chapter exercises). The addition operator (<b>+</b>) produces a 
  427. temporary <b>HugeInteger object</b> as the sum of a 
  428. <b>HugeInteger</b> and a <b>long int</b> (as in the expression 
  429. <b>bigInteger1 + number</b>), or as the sum of a <b>long int</b> and 
  430. a <b>HugeInteger </b>(as in the expression <b>number + 
  431. bigInteger1</b>). Thus, we require the addition operator to 
  432. be commutative (exactly as it is normally). The 
  433. problem is that the class object must appear on the left 
  434. of the addition operator if that operator is to be 
  435. overloaded as a member function. So, we overload the 
  436. operator as a non-member <b>friend</b> function to allow the <br>
  437.  
  438. </page>
  439. <page>
  440. <b>HugeInteger</b> to appear on the right of the addition. The 
  441. <b>operator+</b> function that deals with the <b>HugeInteger</b> on 
  442. the left can still be a member function. Remember that a 
  443. non-member function need not necessarily be a <b>friend</b> 
  444. if appropriate <i>set</i> and <i>get</i> functions exist in the class's 
  445. <tt><b>public</b></tt> interface, and especially if the <i>set</i> and <i>get</i> 
  446. functions are <b>inlined</b>.<br>
  447.  
  448. </page>
  449. <page>
  450. <b>Select the true statement(s). </b><br>
  451. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. Overloaded assignment operators must be declared as member functions.">
  452. Overloaded assignment operators must be declared as non-member functions.   <br>
  453. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  454. Overloaded operator member functions for binary operators implicitly use this to gain access to the left operand of the operator.  <br>
  455. <component type=button name=b label="Check Your Answer" width=125 height=24>
  456.  
  457. </page>
  458. </section>
  459. <section type=Body name=Default title="8.5 Overloading Stream-Insertion and Stream-Extraction Operators">
  460. <page>
  461. <font size=18 bold>8.5 Overloading Stream-Insertion and 
  462. Stream-Extraction Operators</font><hr>
  463. C++ is able to input and output the built-in data types 
  464. using the stream-extraction operator <b>>></b> and stream-
  465. insertion operator <b><<</b>. These operators are overloaded 
  466. (in the class libraries provided with C++ compilers) to 
  467. process each built-in data type including C-like <b>char *</b> 
  468. strings and pointers. The stream-insertion and stream-
  469. extraction operators also can be overloaded to perform 
  470. input and output for user-defined types. <a href="^Code::c:s0p0"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 8.3</a> 
  471. demonstrates overloading the stream-extraction and 
  472. stream-insertion operators to handle data of a user-<br>
  473.  
  474. </page>
  475. <page>
  476. defined telephone number class called <b>PhoneNumber</b>. 
  477. This program assumes telephone numbers are input 
  478. correctly. We leave it to the exercises to provide error-
  479. checking.<br>
  480. <spacer width=16 height=1>The stream-extraction operator function <b>operator>></b> 
  481. (line 27) takes an <b>istream </b>reference called <b>input</b> and a 
  482. <b>PhoneNumber</b> reference called <b>num</b> as arguments, and 
  483. returns an <b>istream</b> reference. Operator function 
  484. <b>operator>></b> is used to input phone numbers of the form<br>
  485. <font size=2><br></font><font size=11><pre>
  486. (800) 555-1212<p>
  487. </pre></font>
  488. into objects of class <b>PhoneNumber</b>. When the 
  489. compiler sees the expression <br>
  490. <font size=2><br></font><font size=11><pre>
  491. cin >> phone<p>
  492. </pre></font>
  493.  
  494. </page>
  495. <page>
  496. in <b>main</b>, the compiler generates the function call <br>
  497. <font size=2><br></font><font size=11><pre>
  498. operator>>( cin, phone );<p>
  499. </pre></font>
  500. When this call is executed, reference parameter <b>input</b> 
  501. becomes an alias for <b>cin</b> and reference parameter <b>num</b> 
  502. becomes an alias for <b>phone</b>. The operator function 
  503. reads as strings the three parts of the telephone number 
  504. into the <b>areaCode</b>, <b>exchange</b>, and <b>line</b> members of the 
  505. referenced <b>PhoneNumber</b> object (<b>num</b> in the operator 
  506. function and <b>phone</b> in <b>main</b>). Stream manipulator <tt><b>setw</b></tt> 
  507. ensures that the proper number of characters is read into 
  508. each character array. Remember that, when used with 
  509. <b>cin</b>, <b>setw</b> restricts the number of characters read to one 
  510. less than its argument (i.e., <b>setw( 4 )</b> allows three <br>
  511.  
  512. </page>
  513. <page>
  514. characters to be read and saves one position for a 
  515. terminating null character). The parentheses, space, and 
  516. dash characters are skipped by calling <b>istream</b> member 
  517. function <b>ignore</b> which discards the specified number of 
  518. characters in the input stream (one character by 
  519. default). Function <b>operator>></b> returns <b>istream</b> 
  520. reference <b>input</b> (i.e., <b>cin</b>). This enables input operations 
  521. on <b>PhoneNumber</b> objects to be cascaded with input 
  522. operations on other <b>PhoneNumber</b> objects or on 
  523. objects of other data types. For example, two 
  524. <b>PhoneNumber</b> objects could be input as follows:<br>
  525. <font size=2><br></font><font size=11><pre>
  526. cin >> phone1 >> phone2;<p>
  527. </pre></font>
  528.  
  529. </page>
  530. <page>
  531. First, the expression <b>cin >> phone1</b> would execute by 
  532. making the call<br>
  533. <font size=2><br></font><font size=11><pre>
  534. operator>>( cin, phone1 );<p>
  535. </pre></font>
  536. This call would then return a reference to <b>cin</b> as the 
  537. value of <b>cin >> phone1</b> so the remaining portion of the 
  538. expression would be interpreted simply as <b>cin >> 
  539. phone2</b>. This would execute by making the call<br>
  540. <font size=2><br></font><font size=11><pre>
  541. operator>>( cin, phone2 );<p>
  542. </pre></font>
  543. The stream-insertion operator takes an <b>ostream</b> 
  544. reference (<b>output</b>) and a reference (<b>num</b>) to a user-
  545. defined type (<b>PhoneNumber</b>) as arguments, and 
  546. returns an <b>ostream</b> reference. Function <b>operator<<</b> <br>
  547.  
  548. </page>
  549. <page>
  550. displays objects of type <b>PhoneNumber</b>. When the 
  551. compiler sees the expression <br>
  552. <font size=2><br></font><font size=11><pre>
  553. cout << phone<p>
  554. </pre></font>
  555. in <b>main</b>, the compiler generates the non-member 
  556. function call <br>
  557. <font size=2><br></font><font size=11><pre>
  558. operator<<( cout, phone );<p>
  559. </pre></font>
  560. Function <b>operator<<</b> displays the parts of the 
  561. telephone number as strings because they are stored in 
  562. string format.<br>
  563. <spacer width=16 height=1>Note that the functions <b>operator>></b> and <b>operator<<</b> 
  564. are declared in <b>class PhoneNumber</b> as non-member, 
  565. <b>friend </b>functions. These operators must be non-
  566. members because the object of class <b>PhoneNumber</b> <br>
  567.  
  568. </page>
  569. <page>
  570. appears in each case as the right operand of the 
  571. operator; the class operand must appear on the left of 
  572. the operator to overload that operator as a member 
  573. function. Overloaded  <a href="^Engineer::c:s0p2"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>input and output operators are 
  574. declared as <tt><b>friends</b></tt> if they need to access non-<b>public</b> 
  575. class members directly for performance reasons. Also 
  576. note that the <b>PhoneNumber</b> reference in <b>operator<<</b>'s 
  577. parameter list is <tt><b>const </b></tt>(because the <b>PhoneNumber</b> will 
  578. simply be output) and the <b>PhoneNumber</b> reference in 
  579. <b>operator>></b>'s parameter list is non-<b>const</b> (because the 
  580. <b>PhoneNumber</b> object must be modified to store the 
  581. input telephone number in the object). <br>
  582.  
  583. </page>
  584. </section>
  585. <section type=Body name=Default title="8.6 Overloading Unary Operators">
  586. <page>
  587. <font size=18 bold>8.6 Overloading Unary Operators</font><hr>
  588. A unary operator for a class can be overloaded as a non-
  589. <b>static</b> member function with no arguments or as a non-
  590. member function with one argument; that argument 
  591. must be either an object of the class or a reference to an 
  592. object of the class. Member functions that implement 
  593. overloaded operators must be non-<b>static</b> so they can 
  594. access the non-<b>static</b> data of the class. Remember that 
  595. <b>static</b> member functions can only access <b>static</b> data 
  596. members of the class.<br>
  597. <spacer width=16 height=1>Later in this chapter, we will overload unary operator <b>!</b> 
  598. to test if an object of our <b>String</b> class is empty and <br>
  599.  
  600. </page>
  601. <page>
  602. return a <b>bool</b> result. When overloading a unary operator 
  603. such as <b>!</b> as a non-<b>static</b> member function with no 
  604. arguments, if <b>s</b> is a <b>String</b> class object or a reference to 
  605. a <b>String</b> class object, when the compiler sees the 
  606. expression <b>!s</b> the compiler generates the call 
  607. <b>s.operator!()</b>. The operand <b>s</b> is the class object for 
  608. which the <b>String</b> class member function <b>operator!</b> is 
  609. being invoked. The function is declared in the class 
  610. definition as follows:<br>
  611. <font size=2><br></font><font size=11><pre>
  612. class String {<p>
  613. public:<p>
  614.    bool operator!() const;<p>
  615.    ...<p>
  616. };<p>
  617. </pre></font>
  618.  
  619. </page>
  620. <page>
  621. A unary operator such as <b>!</b> may be overloaded as a non-
  622. member function with one argument two different 
  623. ways--either with an argument that is an object (this 
  624. requires a copy of the object, so the side effects of the 
  625. function are not applied to the original object), or with 
  626. an argument that is a reference to an object (no copy of 
  627. the original object is made, so all side effects of this 
  628. function are applied to the original object). If <b>s</b> is a 
  629. <b>String </b> <a href="^Practice::c:s0p5"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>class object (or a reference to a <b>String</b> class 
  630. object), then !<b>s </b>is treated as if the call <b>operator!( s ) 
  631. </b>had been written, invoking the non-member <b>friend</b> 
  632. function of class <b>String</b> declared below:<br>
  633.  
  634. </page>
  635. <page>
  636. <font size=2><br></font><font size=11><pre>
  637. class String {<p>
  638.    friend bool operator!( const String & );<p>
  639.    ...<p>
  640. };<p>
  641. </pre></font>
  642.  
  643. </page>
  644. <page>
  645. <b>Select the true statement(s). </b><br>
  646. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  647. A unary operator can be overloaded as a non-static member function.  <br>
  648. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. The member function can be qualified as const.">
  649. A member function that represents an overloaded unary operator cannot be const.   <br>
  650. <component type=button name=b label="Check Your Answer" width=125 height=24>
  651.  
  652. </page>
  653. </section>
  654. <section type=Body name=Default title="8.7 Overloading Binary Operators">
  655. <page>
  656. <font size=18 bold>8.7 Overloading Binary Operators</font><hr>
  657. A binary operator can be overloaded as a non-<b>static</b> 
  658. member function with one argument, or as a non-
  659. member function with two arguments (one of those 
  660. arguments must be either a class object or a reference to 
  661. a class object).<br>
  662. <spacer width=16 height=1>Later in this chapter, we will overload <b>+=</b> to indicate 
  663. concatenation of two string objects. When overloading 
  664. binary operator <b>+=</b> as a non-<b>static</b> member function of 
  665. a <b>String</b> class with one argument, if <b>y</b> and <b>z</b> are <b>String 
  666. </b>class objects, then <b>y += z </b>is treated as if <br>
  667.  
  668. </page>
  669. <page>
  670. <b>y.operator+=( z )</b> had been written, invoking the 
  671. <b>operator+= </b>member function declared below<br>
  672. <font size=2><br></font><font size=11><pre>
  673. class String {<p>
  674. public:<p>
  675.    const String &operator+=( const String & );<p>
  676.    ...<p>
  677. };<p>
  678. </pre></font>
  679. If binary operator <b>+= </b>is to be overloaded as a non-
  680. member function, it must take two arguments--one of 
  681. which must be a class object or a reference to a class 
  682. object. If <b>y</b> and <b>z</b> are <b>String</b> class objects or references 
  683. to <b>String</b> class objects, then <b>y += z</b> is treated as if the 
  684. call <b>operator+=( y, z ) </b>had been written in the program, <br>
  685.  
  686. </page>
  687. <page>
  688. invoking non-member, <b>friend</b> function <b>operator+=</b> 
  689. declared below<br>
  690. <font size=2><br></font><font size=11><pre>
  691. class String {<p>
  692.    friend const String &operator+=( String &, <p>
  693.                                    const String & );<p>
  694.    ...<p>
  695. };<p>
  696. </pre></font>
  697.  
  698. </page>
  699. <page>
  700. <b>Select the true statement(s). </b><br>
  701. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  702. A binary operator can be overloaded as a non-static member function taking one argument.  <br>
  703. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. Such a function must take two arguments.">
  704. A binary operator can be overloaded as a non-member function taking one argument.  <br>
  705. <component type=button name=b label="Check Your Answer" width=125 height=24>
  706.  
  707. </page>
  708. </section>
  709. <section type=Body name=Default title="8.8 Case Study: An Array Class">
  710. <page>
  711. <font size=18 bold>8.8 Case Study: An Array Class</font><hr>
  712. Array notation in C++ is just an alternative to pointers, 
  713. so arrays have much potential for errors. For example, a 
  714. program can easily "walk off" either end of an array 
  715. because C++ does not check whether subscripts fall 
  716. outside the range of an array. Arrays of size <i>n </i>must 
  717. number their elements 0, ..., <i>n</i>  1; alternate subscript 
  718. ranges are not allowed. An entire array cannot be input 
  719. or output at once; each array element must be read or 
  720. written individually. Two arrays cannot be 
  721. meaningfully compared with equality operators or 
  722. relational operators (because the array names are <br>
  723.  
  724. </page>
  725. <page>
  726. simply pointers to where the arrays begin in memory). 
  727. When an array is passed to a general-purpose function 
  728. designed to handle arrays of any size, the size of the 
  729. array must be passed as an additional argument. One 
  730. array cannot be assigned to another with the assignment 
  731. operator(s) (because array names are <tt><b>const</b></tt> pointers and 
  732. a constant pointer cannot be used on the left side of an 
  733. assignment operator). These and other capabilities 
  734. certainly seem like "naturals" for dealing with arrays, 
  735. but C++ does not provide such capabilities. However, 
  736. C++ does provide the means to implement such array 
  737. capabilities through the mechanisms of operator 
  738. overloading.<br>
  739.  
  740. </page>
  741. <page>
  742. In this example, we develop an array class that 
  743. performs range checking to ensure that subscripts 
  744. remain within the bounds of the array. The class allows 
  745. one array object to be assigned to another with the 
  746. assignment operator. Objects of this array class 
  747. automatically know their size so the size does not need 
  748. to be passed separately as an argument when passing an 
  749. array to a function. Entire arrays can be input or output 
  750. with the stream-extraction and stream-insertion 
  751. operators, respectively. Array comparisons can be made 
  752. with the equality operators <b>==</b> and <b>!=</b>. Our array class 
  753. uses a <b>static</b> member to keep track of the number of 
  754. array objects that have been instantiated in the program. <br>
  755.  
  756. </page>
  757. <page>
  758. This example will sharpen your appreciation of data 
  759. abstraction. You will probably want to suggest many 
  760. enhancements to this array class. Class development is 
  761. an interesting, creative, and intellectually challenging 
  762. activity--always with the goal of "crafting valuable 
  763. classes."<br>
  764. <spacer width=16 height=1>The program of <a href="^Code::c:s0p1"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 8.4</a> demonstrates class <b>Array</b> and 
  765. its overloaded operators. First we walk through the 
  766. driver program in <b>main</b>. Then we consider the class 
  767. definition and each of the class's member function and 
  768. <tt><b>friend</b></tt> function definitions. <br>
  769. <spacer width=16 height=1>The <tt><b>static</b></tt> class variable <b>arrayCount</b> of class <b>Array</b> 
  770. contains the number of <b>Array</b> objects instantiated <br>
  771.  
  772. </page>
  773. <page>
  774. during program execution. The program begins by 
  775. using <b>static</b> member function <b>getArrayCount</b> (line 
  776. 176) to retrieve the number of arrays instantiated so far. 
  777. Next, the program instantiates two objects of class 
  778. <b>Array</b> (line 179)--<b>integers1</b> with seven elements and 
  779. <b>integers2</b> with default size 10 elements (the default 
  780. value specified by the <b>Array</b> default constructor). Line 
  781. 181 calls function <b>getArrayCount</b> again to retrieve the 
  782. value of class variable <b>arrayCount</b>. Lines 184 through 
  783. 187 use member function <b>getSize</b> to determine the size 
  784. of <b>Array integers1</b> and output <b>integers1</b> using the 
  785. <b>Array</b> overloaded stream-insertion operator to confirm 
  786. that the array elements were initialized correctly by the <br>
  787.  
  788. </page>
  789. <page>
  790. constructor. Next, lines 190 through 193 output the size 
  791. of array <b>integers2</b> and output <b>integers2</b> using the 
  792. <b>Array</b> overloaded stream-insertion operator.<br>
  793. <spacer width=16 height=1>The user is then prompted to input 17 integers. The 
  794. <b>Array</b> overloaded stream-extraction operator is used to 
  795. read these values into both arrays with line 197 <br>
  796. <font size=2><br></font><font size=11><pre>
  797. cin >> integers1 >> integers2;<p>
  798. </pre></font>
  799. The first seven values are stored in <b>integers1</b> and the 
  800. remaining 10 values are stored in <b>integers2</b>. In lines 
  801. 198 through 200, the two arrays are output with the 
  802. <b>Array</b> stream-insertion operator to confirm that the 
  803. input was performed correctly.<br>
  804.  
  805. </page>
  806. <page>
  807. Line 204 tests the overloaded inequality operator by 
  808. evaluating the condition<br>
  809. <font size=2><br></font><font size=11><pre>
  810. integers1 != integers2<p>
  811. </pre></font>
  812. and the program reports that the arrays are indeed not 
  813. equal.<br>
  814. <spacer width=16 height=1>Line 209 instantiates a third <b>Array</b> called <b>integers3</b> and 
  815. initializes it with <b>Array integers1</b>. This invokes the 
  816. <b>Array</b> <i>copy constructor</i> to copy the elements of 
  817. <b>integers1</b> into <b>integers3</b>. We discuss the details of the 
  818. copy constructor shortly. <br>
  819. <spacer width=16 height=1>Lines 211 through 214 output the size of <b>integers3</b> and 
  820. output <b>integers3</b> using the <b>Array </b>overloaded stream-<br>
  821.  
  822. </page>
  823. <page>
  824. insertion operator to confirm that the array elements 
  825. were initialized correctly by the constructor. <br>
  826. <spacer width=16 height=1>Next, line 218 tests the overloaded assignment operator 
  827. (<b>=</b>) with the statement<br>
  828. <font size=2><br></font><font size=11><pre>
  829. integers1 = integers2;<p>
  830. </pre></font>
  831. Both <b>Arrays</b> are printed in lines 219 and 220 to 
  832. confirm that the assignment was successful. It is 
  833. interesting to note that <b>integers1</b> originally held 7 
  834. integers and needed to be resized to hold a copy of the 
  835. 10 elements in <b>integers2</b>. As we will see, the 
  836. overloaded assignment operator performs this resizing 
  837. in a manner transparent to the invoker of the operator.<br>
  838.  
  839. </page>
  840. <page>
  841. Next, line 224 uses the overloaded equality operator 
  842. (<b>==</b>) to confirm that objects <b>integers1</b> and <b>integers2</b> 
  843. are indeed identical after the assignment.<br>
  844. <spacer width=16 height=1>Line 228 uses the overloaded subscript operator to refer 
  845. to <b>integers1[ 5 ]</b>--an in-range element of <b>integers1</b>. 
  846. This subscripted name is used as an <i>rvalue</i> to print the 
  847. value in i<b>ntegers1[ 5 ].</b> Line 232, uses i<b>ntegers1[ 5 ]</b> 
  848. as an <i>lvalue</i> on the left side of an assignment statement 
  849. to assign a new value, <b>1000</b>, to element <b>5</b> of <b>integers1</b>. 
  850. Note that <b>operator[]</b> returns the reference to use as the 
  851. <i>lvalue</i> after it determines that <b>5</b> is in range for 
  852. <b>integers1</b>.<br>
  853.  
  854. </page>
  855. <page>
  856. Line 237 attempts to assign the value <b>1000</b> to 
  857. <b>integers1[ 15 ]</b>--an out-of-range element. The <b>Array</b> 
  858. overloaded <b>[]</b> operator catches this error and terminates 
  859. abnormally.<br>
  860. <spacer width=16 height=1>Interestingly, the array subscript operator <b>[]</b> is not 
  861. restricted for use only with arrays; it can be used to 
  862. select elements from other kinds of ordered container 
  863. classes such as linked lists, strings, dictionaries, and so 
  864. on. Also, subscripts no longer have to be integers; 
  865. characters, strings, floats or even objects of user-
  866. defined classes could be used, for example.<br>
  867.  
  868. </page>
  869. <page>
  870. Now that we have seen how this program operates, let 
  871. us walk through the class header and the member 
  872. function definitions. Lines 29 through 31<br>
  873. <font size=2><br></font><font size=11><pre>
  874. int size; // size of the array<p>
  875. int *ptr; // pointer to first element of array<p>
  876. static int arrayCount;  // # of Arrays instantiated<p>
  877. </pre></font>
  878. represent the <b>private</b> data members of the class. The 
  879. array consists of a <b>size</b> member indicating the number 
  880. of elements in the array, an <b>int</b> pointer--<b>ptr</b>--that will 
  881. point to the dynamically allocated array of integers 
  882. stored in an <b>Array</b> object, and <b>static</b> member 
  883. <b>arrayCount</b> indicating the number of array objects that 
  884. have been instantiated.<br>
  885.  
  886. </page>
  887. <page>
  888. Lines 9 and 10<br>
  889. <font size=2><br></font><font size=11><pre>
  890. friend ostream &operator<<( ostream &, <p>
  891.                             const Array & );<p>
  892. friend istream &operator>>( istream &, Array & );<p>
  893. </pre></font>
  894. declare the overloaded stream-insertion operator and 
  895. the overloaded stream-extraction operator to be <b>friends</b> 
  896. of class <b>Array</b>. When the compiler sees an expression 
  897. like <br>
  898. <font size=2><br></font><font size=11><pre>
  899. cout << arrayObject<p>
  900. </pre></font>
  901. it invokes the <b>operator<<</b>( <b>ostream &, const Array 
  902. & </b>) function by generating the call <br>
  903. <font size=2><br></font><font size=11><pre>
  904. operator<<( cout, arrayObject )<p>
  905. </pre></font>
  906. When the compiler sees an expression like <br>
  907.  
  908. </page>
  909. <page>
  910. <font size=2><br></font><font size=11><pre>
  911. cin >> arrayObject<p>
  912. </pre></font>
  913. it invokes the <b>operator>>( istream &, Array & ) 
  914. </b>function by generating the call<br>
  915. <font size=2><br></font><font size=11><pre>
  916. operator>>( cin, arrayObject )<p>
  917. </pre></font>
  918. We note again that these stream-insertion and stream-
  919. extraction operator functions cannot be members of 
  920. class <b>Array</b> because the <b>Array</b> object is always 
  921. mentioned on the right side of a stream-insertion 
  922. operator and a stream-extraction operator. If these 
  923. operator functions were to be members of class <b>Array</b>, 
  924. the following awkward statements would have to be 
  925. used to output and input an <b>Array</b>:<br>
  926.  
  927. </page>
  928. <page>
  929. <font size=2><br></font><font size=11><pre>
  930. arrayObject << cout;<p>
  931. arrayObject >> cin;<p>
  932. </pre></font>
  933. Function <b>operator<<</b> (defined at line 151) prints the 
  934. number of elements indicated by the <b>size</b> from the array 
  935. stored at <b>ptr</b>. Function <b>operator>></b> (defined at line 142) 
  936. inputs directly into the array pointed to by <b>ptr</b>. Each of 
  937. these operator functions returns an appropriate 
  938. reference to enable cascaded output or input statements, 
  939. respectively.<br>
  940. <spacer width=16 height=1>The line<br>
  941. <font size=2><br></font><font size=11><pre>
  942. Array( int = 10 );               // default constructor<p>
  943. </pre></font>
  944.  
  945. </page>
  946. <page>
  947. declares the default constructor for the class and 
  948. specifies that the array size defaults to 10 elements. 
  949. When the compiler sees a declaration like <br>
  950. <font size=2><br></font><font size=11><pre>
  951. Array integers1( 7 );<p>
  952. </pre></font>
  953. or the equivalent form<br>
  954. <font size=2><br></font><font size=11><pre>
  955. Array integers1 = 7;<p>
  956. </pre></font>
  957. it invokes the default constructor (remember that the 
  958. default constructor in this example actually receives a 
  959. single <tt><b>int</b></tt> argument that has a default value of 10). 
  960. The default constructor (defined at line 47) validates 
  961. and assigns the argument to the size data member, 
  962. uses new to obtain the space to hold the internal 
  963. representation of this array and assigns the pointer <br>
  964.  
  965. </page>
  966. <page>
  967. returned by new to data member ptr, uses assert to 
  968. test that new was successful, increments 
  969. arrayCount, then uses a for loop to initialize all the 
  970. elements of the array to zero. It is possible to have an 
  971. Array class that does not initialize its members if, for 
  972. example, these members are to be read at some later 
  973. time. But this is considered to be a poor programming 
  974. practice. <b>Arrays</b>, and objects in general, should be 
  975. maintained at all times in a properly initialized and 
  976. consistent state.<br>
  977. <spacer width=16 height=1>Line 13<br>
  978. <font size=2><br></font><font size=11><pre>
  979. Array( const Array & );            // copy constructor<p>
  980. </pre></font>
  981.  
  982. </page>
  983. <page>
  984. declares a <i>copy constructor</i> (defined at line 60) that 
  985. initializes an <b>Array</b> by making a copy of an existing 
  986. <b>Array</b> object. Such copying must be done carefully to 
  987. avoid the pitfall of leaving both <b>Array</b> objects pointing 
  988. to the same dynamically allocated storage, exactly the 
  989. problem that would occur with default memberwise 
  990. copy. Copy constructors are invoked whenever a copy 
  991. of an object is needed such as in call-by-value, when 
  992. returning an object by value from a called function, or 
  993. when initializing an object to be a copy of another 
  994. object of the same class. The copy constructor is called 
  995. in a definition when an object of class <b>Array</b> is <br>
  996.  
  997. </page>
  998. <page>
  999. instantiated and initialized with another object of class 
  1000. <b>Array</b> as in the following declaration:<br>
  1001. <font size=2><br></font><font size=11><pre>
  1002. Array integers3( integers1 );<p>
  1003. </pre></font>
  1004. or the equivalent declaration<br>
  1005. <font size=2><br></font><font size=11><pre>
  1006. Array integers3 = integers1;<p>
  1007. </pre></font>
  1008. The  <a href="^Errors::c:s0p6"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>copy  <a href="^Errors::c:s0p8"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>constructor member function <b>Array</b> uses a 
  1009. member initializer to copy the <b>size</b> of the array used for 
  1010. initialization into the <b>size</b> data member, uses <b>new</b> to 
  1011. obtain the space to hold the internal representation of 
  1012. this array and assigns the pointer returned by <b>new</b> to 
  1013. data member <b>ptr</b>, uses <b>assert</b> to test that <b>new</b> was 
  1014. successful, increments <b>arrayCount</b>, then uses a <b>for</b> <br>
  1015.  
  1016. </page>
  1017. <page>
  1018. loop to copy all the elements of the initializer array into 
  1019. this array. <br>
  1020. <spacer width=16 height=1>Line 14<br>
  1021. <font size=2><br></font><font size=11><pre>
  1022. ~Array();                        // destructor<p>
  1023. </pre></font>
  1024. declares the destructor (defined at line 71) for the class. 
  1025. The  <a href="^Engineer::c:s0p4"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>destructor is invoked automatically when the life 
  1026. of an object of class <b>Array</b> is terminated. The 
  1027. destructor uses <b>delete []</b> to reclaim the dynamic storage 
  1028. allocated by <b>new</b> in the constructor then decrements 
  1029. <b>arrayCount</b>.<br>
  1030. <spacer width=16 height=1>Line 15<br>
  1031. <font size=2><br></font><font size=11><pre>
  1032. int getSize() const;             // return size<p>
  1033. </pre></font>
  1034. declares a function that reads the size of the array.<br>
  1035.  
  1036. </page>
  1037. <page>
  1038. Line 16<br>
  1039. <font size=2><br></font><font size=11><pre>
  1040. const Array &operator=( const Array & ); <p>
  1041.     // assign arrays<p>
  1042. </pre></font>
  1043. declares the overloaded assignment operator function 
  1044. for the class. When the compiler sees an expression like<br>
  1045. <font size=2><br></font><font size=11><pre>
  1046. integers1 = integers2;<p>
  1047. </pre></font>
  1048. it invokes the <b>operator=</b> function by generating the call<br>
  1049. <font size=2><br></font><font size=11><pre>
  1050. integers1.operator=( integers2 )<p>
  1051. </pre></font>
  1052. The  <b>operator=</b> <a href="^Engineer::c:s0p6"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>member function (defined at line 82) 
  1053. tests for <i>self assignment</i>. If a self assignment is being 
  1054. attempted, the  <a href="^Errors::c:s0p10"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>assignment is skipped (i.e., the object 
  1055. already is itself; in a moment we will see why self-
  1056. assignment is dangerous). If it is not a self  <a href="^Engineer::c:s0p5"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>assignment, <br>
  1057.  
  1058. </page>
  1059. <page>
  1060. then the member function determines if the sizes of the 
  1061. two arrays are identical--in which case the original 
  1062. array of integers in the left-side <b>Array</b> object is not 
  1063. reallocated. Otherwise, <b>operator=</b> uses <b>delete </b>to 
  1064. reclaim the space originally allocated in the target array, 
  1065. copies the <b>size</b> of the source array to the <b>size</b> of the 
  1066. target array, uses <b>new</b> to allocate that amount of space 
  1067. for the target array and places the pointer returned by 
  1068. <b>new</b> into the array's <b>ptr</b> member, and uses <b>assert</b> to 
  1069. verify that new succeeded. Then, <b>operator=</b> uses a <b>for</b> 
  1070. loop to copy the array elements from the source array to 
  1071. the target array. Regardless of whether this is a self 
  1072. assignment or not, the member function then returns the <br>
  1073.  
  1074. </page>
  1075. <page>
  1076. current object (i.e., <b>*this</b>) as a constant reference; this 
  1077. enables cascaded <b>Array</b> assignments such as <b>x = y = z</b>. <br>
  1078. <spacer width=16 height=1>Line 17<br>
  1079. <font size=2><br></font><font size=11><pre>
  1080. bool operator==( const Array & ) const;  <p>
  1081.     // compare equal<p>
  1082. </pre></font>
  1083. declares the overloaded equality operator (<b>==</b>) for the 
  1084. class. When the compiler sees the expression <br>
  1085. <font size=2><br></font><font size=11><pre>
  1086. integers1 == integers2<p>
  1087. </pre></font>
  1088. in <b>main</b>, the compiler invokes the <b>operator==</b> member 
  1089. function by generating the call<br>
  1090. <font size=2><br></font><font size=11><pre>
  1091. integers1.operator==( integers2 )<p>
  1092. </pre></font>
  1093. The <b>operator== </b>member function (defined at line 104) 
  1094. immediately returns <tt><b>false</b></tt> if the <b>size</b> members of the <br>
  1095.  
  1096. </page>
  1097. <page>
  1098. arrays are different. Otherwise, the member function 
  1099. compares each pair of elements. If they are all the same, 
  1100. <tt><b>true</b></tt> is returned. The first pair of elements to differ 
  1101. causes <b>false</b> to be returned immediately.<br>
  1102. <spacer width=16 height=1>Lines 21 and 22<br>
  1103. <font size=2><br></font><font size=11><pre>
  1104. bool operator!=( const Array &right ) const  <p>
  1105.    { return ! ( *this == right ); }<p>
  1106. </pre></font>
  1107. define the overloaded inequality operator (<b>!=</b>) for the 
  1108. class. The <b>operator!=</b> member function is defined in 
  1109. terms of the overloaded equality operator. The function 
  1110. definition uses the overloaded <b>operator== </b>function to 
  1111. determine if one <b>Array</b> is equal to another, then returns 
  1112. the opposite of that result. Writing the <b>operator!=</b> <br>
  1113.  
  1114. </page>
  1115. <page>
  1116. function in this manner enables the programmer to 
  1117. reuse the <b>operator==</b> function and reduces the amount 
  1118. of code that must be written in the class. Also, note that 
  1119. the full function definition for <b>operator!=</b> is in the 
  1120. <b>Array</b> header file. This allows the compiler to <b>inline</b> 
  1121. the definition of <b>operator!=</b> to eliminate the overhead 
  1122. of the extra function call.<br>
  1123. <spacer width=16 height=1>Lines 24 and 25<br>
  1124. <font size=2><br></font><font size=11><pre>
  1125. int &operator[]( int );              <p>
  1126.     // subscript operator<p>
  1127. const int &operator[]( int ) const;  <p>
  1128.     // subscript operator<p>
  1129. </pre></font>
  1130.  
  1131. </page>
  1132. <page>
  1133. declare two overloaded subscript operators (defined at 
  1134. lines 118 and 128, respectively) for the class. When the 
  1135. compiler sees the expression<br>
  1136. <font size=2><br></font><font size=11><pre>
  1137. integers1[ 5 ]<p>
  1138. </pre></font>
  1139. in <b>main</b>, the compiler invokes the appropriate 
  1140. overloaded <b>operator[]</b> member function by generating 
  1141. the call<br>
  1142. <font size=2><br></font><font size=11><pre>
  1143. integers1.operator[]( 5 )<p>
  1144. </pre></font>
  1145. The compiler creates a call to the <b>const</b> version of 
  1146. <b>operator[] </b>when the subscript operator is used on a 
  1147. <b>const Array</b> object. Each definition of <b>operator[]</b> tests 
  1148. if the subscript is in range, and, if it is not, the program 
  1149. terminates abnormally. If the subscript is in range, the <br>
  1150.  
  1151. </page>
  1152. <page>
  1153. appropriate element of the array is returned as a 
  1154. reference so that it may be used as an <i>lvalue</i> (for 
  1155. example, on the left side of an assignment statement) in 
  1156. the case of the non-<b>const</b> version of <b>operator[]</b>, or an 
  1157. <i>rvalue</i> in the case of the <b>const</b> version of <b>operator[]</b>.<br>
  1158. <spacer width=16 height=1>Line 26<br>
  1159. <font size=2><br></font><font size=11><pre>
  1160. static int getArrayCount(); // return count of Arrays<p>
  1161. </pre></font>
  1162. declares <b>static</b> function <b>getArrayCount</b> that returns the 
  1163. value of <b>static</b> data member <b>arrayCount</b>, even if no 
  1164. objects of class <b>Array</b> exist.<br>
  1165.  
  1166. </page>
  1167. </section>
  1168. <section type=Body name=Default title="8.9 Converting Between Types">
  1169. <page>
  1170. <font size=18 bold>8.9 Converting Between Types</font><hr>
  1171. Most programs process information of a variety of 
  1172. types. Sometimes all the operations "stay within a 
  1173. type." For example, adding an integer to an integer 
  1174. produces an integer (as long as the result is not too large 
  1175. to be represented as an integer). But, it is often 
  1176. necessary to convert data of one type to data of another 
  1177. type. This can happen in assignments, in calculations, 
  1178. in passing values to functions, and in returning values 
  1179. from functions. The compiler knows how to perform 
  1180. certain conversions among built-in types. Programmers 
  1181. can force conversions among built-in types by casting.<br>
  1182.  
  1183. </page>
  1184. <page>
  1185. But what about user-defined types? The compiler 
  1186. cannot automatically know how to convert among user-
  1187. defined types and built-in types. The programmer must 
  1188. specify how such conversions are to occur. Such 
  1189. conversions can be performed with <i>conversion 
  1190. constructors</i>--single-argument constructors that turn 
  1191. objects of other types (including built-in types) into 
  1192. objects of a particular class. We will use a conversion 
  1193. constructor later in this chapter to convert ordinary 
  1194. <b>char *</b> strings into <b>String</b> class objects.<br>
  1195. <spacer width=16 height=1>A <i>conversion operator</i> (also called a <i>cast operator</i>) can 
  1196. be used to convert an object of one class into an object 
  1197. of another class or into an object of a built-in type. Such <br>
  1198.  
  1199. </page>
  1200. <page>
  1201. a conversion operator must be a non-<b>static</b> member 
  1202. function; this kind of conversion operator cannot be a 
  1203. <b>friend</b> function. <br>
  1204. <spacer width=16 height=1>The function prototype<br>
  1205. <font size=2><br></font><font size=11><pre>
  1206. A::operator char *() const;<p>
  1207. </pre></font>
  1208. declares an overloaded cast operator function for 
  1209. creating a temporary <b>char * </b>object out of an object of 
  1210. user-defined type A. An overloaded <i>cast operator 
  1211. function</i> does not specify a return type--the return type 
  1212. is the type to which the object is being converted. If <b>s</b> is 
  1213. a class object, when the compiler sees the expression 
  1214. <b>(char *) s </b>the compiler generates the call <b>s.operator 
  1215. </b><br>
  1216.  
  1217. </page>
  1218. <page>
  1219. <b>char</b> <b>*()</b>. The operand <b>s</b> is the class object <b>s</b> for which 
  1220. the member function <b>operator char *</b> is being invoked.<br>
  1221. <spacer width=16 height=1>Overloaded cast operator functions can be defined for 
  1222. converting objects of user-defined types into built-in 
  1223. types or into objects of other user-defined types. The 
  1224. prototypes<br>
  1225. <font size=2><br></font><font size=11><pre>
  1226. A::operator int() const;<p>
  1227. A::operator otherClass() const;<p>
  1228. </pre></font>
  1229. declare overloaded cast operator functions for 
  1230. converting an object of user-defined type <b>A</b> into an 
  1231. integer and for converting an object of user-defined 
  1232. type <b>A</b> into an object of user-defined type <b>otherClass</b>. <br>
  1233.  
  1234. </page>
  1235. <page>
  1236. One of the nice features of cast operators and 
  1237. conversion constructors is that, when necessary, the 
  1238. compiler can call these functions automatically to 
  1239. create temporary objects. For example, if an object <b>s</b> of 
  1240. a user-defined <b>String</b> class appears in a program at a 
  1241. location where an ordinary <b>char *</b> is expected, such as<br>
  1242. <font size=2><br></font><font size=11><pre>
  1243. cout << s;<p>
  1244. </pre></font>
  1245. the compiler calls the overloaded cast operator function 
  1246. <b>operator char *</b> to convert the object into a <b>char *</b> and 
  1247. uses the resulting <b>char * </b>in the expression. With this 
  1248. cast operator provided for our <b>String</b> class, the stream-
  1249. insertion operator does not have to be overloaded to 
  1250. output a <b>String</b> using <b>cout</b>.<br>
  1251.  
  1252. </page>
  1253. <page>
  1254. <b>Select the true statement(s). </b><br>
  1255. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  1256. A conversion operator converts an object of one class into an object of another class.  <br>
  1257. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. Overloaded cast operator functions never specify a return type.">
  1258. An overloaded cast operator function specifies a return type. <br>
  1259. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  1260. When necessary, the compiler will automatically call a conversion constructor to create a temporary object.  <br>
  1261. <component type=button name=b label="Check Your Answer" width=125 height=24>
  1262.  
  1263. </page>
  1264. </section>
  1265. <section type=Body name=Default title="8.10 Case Study: A String Class">
  1266. <page>
  1267. <font size=18 bold>8.10 Case Study: A String Class</font><hr>
  1268. As a capstone exercise to our study of overloading, we 
  1269. will build a class that handles the creation and 
  1270. manipulation of strings (<a href="^Code::c:s0p2"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 8.5</a>). Class <b>string</b> is now 
  1271. part of the C++ standard libraries--we study class 
  1272. <b>string</b> in detail in Chapter 19. For now we will make 
  1273. extensive use of operator overloading to craft our own 
  1274. class <b>String</b>.<br>
  1275. <spacer width=16 height=1>First, we present the header for class <b>String</b>. We discuss 
  1276. the <b>private</b> data used for representing <b>String</b> objects. 
  1277. Then we walk through the class's <b>public</b> interface, 
  1278. discussing each of the services the class provides.<br>
  1279.  
  1280. </page>
  1281. <page>
  1282. Next, we will walk through the driver program in <b>main</b>. 
  1283. We will discuss the coding style we "aspire to," i.e., the 
  1284. kinds of concise, operator-intensive expressions we 
  1285. would like to be able to write with objects of our new 
  1286. <b>String</b> class and with the class's collection of 
  1287. overloaded operators.<br>
  1288. <spacer width=16 height=1>Then we discuss the member function definitions for 
  1289. class <b>String</b>. For each of the overloaded operators, we 
  1290. show the code in the driver program that invokes the 
  1291. overloaded operator function, and we explain how the 
  1292. overloaded operator function works.<br>
  1293. We begin with the internal representation of a <b>String</b>. 
  1294. Lines 44 and 45<br>
  1295.  
  1296. </page>
  1297. <page>
  1298. <font size=2><br></font><font size=11><pre>
  1299. int length;       // string length <p>
  1300. char *sPtr;         // pointer to start of string<p>
  1301. </pre></font>
  1302. declare the <b>private</b> data members of the class. Our 
  1303. implementation of a <b>String</b> object has a <b>length</b> field 
  1304. which represents the number of characters in the string 
  1305. not including the null character at the end of the 
  1306. character string and has a pointer <b>sPtr</b> to its 
  1307. dynamically allocated storage representing the 
  1308. character string.<br>
  1309. <spacer width=16 height=1>Now we walk through the <b>String</b> class header file in 
  1310. <a href="^Code::c:s0p2"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 8.5</a>. Lines 9 and 10<br>
  1311. <font size=2><br></font><font size=11><pre>
  1312. friend ostream &operator<<( ostream &, <p>
  1313.                             const String & );<p>
  1314. friend istream &operator>>( istream &, String & );<p>
  1315. </pre></font>
  1316.  
  1317. </page>
  1318. <page>
  1319. declare the overloaded stream-insertion operator 
  1320. function <b>operator<<</b> (defined at line 180) and the 
  1321. overloaded stream-extraction operator function 
  1322. <b>operator>> </b>(defined at line 187) as <b>friends</b> of the 
  1323. class. The implementation of these is straightforward.<br>
  1324. <spacer width=16 height=1>Line 13<br>
  1325. <font size=2><br></font><font size=11><pre>
  1326. String( const char * = "" ); <p>
  1327.     // conversion/default constructor<p>
  1328. </pre></font>
  1329. declares a <i>conversion constructor</i>. This constructor 
  1330. (defined at line 60) takes a <tt><b>const</b></tt> char * argument 
  1331. (that defaults to the empty string) and instantiates a 
  1332. String object which includes that same character 
  1333. string. Any <i>single-argument constructor</i> can be thought <br>
  1334.  
  1335. </page>
  1336. <page>
  1337. of as a conversion constructor. As we will see, such 
  1338. constructors are helpful when we are doing any 
  1339. String operation using char * arguments. The 
  1340. conversion constructor converts the <tt><b>char</b></tt> <tt><b>*</b></tt> string into 
  1341. a String object which is then assigned to the target 
  1342. String object. The availability of this  <a href="^Engineer::c:s0p7"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>conversion 
  1343. constructor means that it is not necessary to supply an 
  1344. overloaded assignment operator for specifically 
  1345. assigning character strings to <b>String</b> objects. The 
  1346. compiler automatically invokes the conversion 
  1347. constructor to create a temporary <b>String</b> object 
  1348. containing the character string. Then, the overloaded <br>
  1349.  
  1350. </page>
  1351. <page>
  1352. assignment operator is invoked to assign the temporary 
  1353. <b>String</b> object to another <b>String</b> object. <br>
  1354. <spacer width=16 height=1>The <b>String</b> conversion constructor could be invoked in 
  1355. a declaration such as <b>String s1( "happy" )</b>. The 
  1356. conversion constructor calculates the length of the 
  1357. character string and assigns this to <b>private</b> data member 
  1358. <b>length</b> in the member initializer list then calls <b>private</b> 
  1359. utility function <b>setString</b>. Function <b>setString</b> (defined 
  1360. at line 172) uses <b>new</b> to attach a sufficient amount of 
  1361. space to <b>private</b> data member <b>sPtr</b>, uses <b>assert</b> to test 
  1362. that <b>new</b> succeeded and, if it did, uses <b>strcpy</b> to copy 
  1363. the character string into the object.<br>
  1364.  
  1365. </page>
  1366. <page>
  1367. Line 14<br>
  1368. <font size=2><br></font><font size=11><pre>
  1369. String( const String & );    // copy constructor<p>
  1370. </pre></font>
  1371. is a copy constructor (defined at line 67) that initializes 
  1372. a <b>String</b> object by making a copy of an existing <b>String</b> 
  1373. object. Such copying must be done carefully to avoid 
  1374. the pitfall of leaving both <b>String</b> objects pointing to the 
  1375. same dynamically allocated storage, exactly the 
  1376. problem that would occur with <i>default memberwise 
  1377. copy</i>. The copy constructor operates similarly to the 
  1378. conversion constructor except that it simply copies the 
  1379. <b>length</b> member from the source <b>String</b> object to the 
  1380. target <b>String</b> object. Note that the copy constructor 
  1381. creates new space for the target object's internal <br>
  1382.  
  1383. </page>
  1384. <page>
  1385. character string. If it simply copied the <b>sPtr</b> in the 
  1386. source object to the target object's <b>sPtr</b>, then both 
  1387. objects would point to the same dynamically allocated 
  1388. storage. The first destructor to execute would then 
  1389. delete the dynamically allocated storage and the other 
  1390. object's <b>sPtr</b> would then be undefined (i.e., <b>sPtr</b> would 
  1391. be a <i>dangling pointer</i>), a situation likely to cause a 
  1392. serious run-time error.<br>
  1393. <spacer width=16 height=1>Line 15<br>
  1394. <font size=2><br></font><font size=11><pre>
  1395. ~String();        // destructor<p>
  1396. </pre></font>
  1397. declares the destructor (defined at line 74) for class 
  1398. <b>String</b>. The destructor uses <b>delete</b> to reclaim the <br>
  1399.  
  1400. </page>
  1401. <page>
  1402. dynamic storage obtained by <b>new</b> to provide the space 
  1403. for the character string. <br>
  1404. <spacer width=16 height=1>Line 16<br>
  1405. <font size=2><br></font><font size=11><pre>
  1406. const String &operator=( const String & );  <p>
  1407.     // assignment<p>
  1408. </pre></font>
  1409. declares the overloaded assignment operator function 
  1410. <b>operator= </b>(defined at line 81). When the compiler sees 
  1411. an expression like <b>string1 = string2</b>, the compiler 
  1412. generates the function call <br>
  1413. <font size=2><br></font><font size=11><pre>
  1414. string1.operator=( string2 ); <p>
  1415. </pre></font>
  1416. The overloaded assignment operator function 
  1417. <b>operator=</b> tests for self-assignment. If this is a self-
  1418. assignment, the function simply returns because the <br>
  1419.  
  1420. </page>
  1421. <page>
  1422. object is already itself. If this test were omitted, the 
  1423. function would immediately delete the space in the 
  1424. target object and thus lose the character string--a 
  1425. classic example of a <i>memory leak</i>. If there is no self-
  1426. assignment, the function does delete the space, copies 
  1427. the <b>length</b> field of the source object to the target object 
  1428. and calls <b>setString</b> (line 172) to create new space for 
  1429. the target object, determine if new succeeded and use 
  1430. <b>strcpy</b> to copy the character string from the source 
  1431. object to the target object. Whether or not this is a self-
  1432. assignment, <b>*this</b> is returned to enable cascaded 
  1433. assignments.<br>
  1434. <spacer width=16 height=1>Line 17<br>
  1435.  
  1436. </page>
  1437. <page>
  1438. <font size=2><br></font><font size=11><pre>
  1439. const String &operator+=( const String & ); <p>
  1440.     // concatenation<p>
  1441. </pre></font>
  1442. declares the overloaded string concatenation operator 
  1443. (defined at line 98). When the compiler sees the 
  1444. expression <b>s1 += s2</b> in <b>main</b>, the function call 
  1445. <b>s1.operator+=( s2 ) </b>is generated. Function <b>operator+=</b> 
  1446. creates a temporary pointer to hold the current object's 
  1447. character string until the character string's memory can 
  1448. be deleted, calculates the combined length of the 
  1449. concatenated string, uses new to reserve space for the 
  1450. string, uses <b>assert</b> to test that new succeeded, uses 
  1451. <b>strcpy</b> to copy the original string into the newly 
  1452. allocated space, uses <b>strcat</b> to concatenate the source <br>
  1453.  
  1454. </page>
  1455. <page>
  1456. object's character string to the newly allocated space, 
  1457. uses <b>delete</b> to reclaim the space occupied by this 
  1458. object's original character string, and returns <b>*this</b> as a 
  1459. <b>String & </b>to enable cascading of <b>+=</b> operators.<br>
  1460. <spacer width=16 height=1>Do we need a second overloaded concatenation 
  1461. operator to allow concatenation of a <b>String</b> and a <b>char 
  1462. *</b>? No. The <b>const char *</b> conversion constructor 
  1463. converts a conventional string into a temporary <b>String</b> 
  1464. object which then matches the existing overloaded 
  1465. concatenation operator. Again, C++ can perform such 
  1466. conversions only one level deep to facilitate a match. 
  1467. C++ can also perform an implicit compiler-defined 
  1468. conversion between built-in types before it performs the <br>
  1469.  
  1470. </page>
  1471. <page>
  1472. conversion between a built-in type and a class. Note 
  1473. that when a temporary <b>String</b> object is created, the 
  1474. conversion constructor and the destructor are called 
  1475. (see the output resulting from <b>s1 += " to you"</b> in <a href="^Code::c:s0p2"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 
  1476. 8.5</a>). This is an example of function call overhead that 
  1477. is hidden from the client of the class when temporary 
  1478. class objects are created and destroyed during  <a href="^Perform::c:s0p2"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>implicit 
  1479. conversions. Similar overhead is generated by copy 
  1480. constructors in call-by-value parameter passing and 
  1481. returning class objects by value.<br>
  1482. <spacer width=16 height=1>Line 18<br>
  1483. <font size=2><br></font><font size=11><pre>
  1484. bool operator!() const;  // is String empty?<p>
  1485. </pre></font>
  1486.  
  1487. </page>
  1488. <page>
  1489. declares the overloaded negation operator (defined at 
  1490. line 111). This operator is commonly used with string 
  1491. classes to test if a string is empty. For example, when 
  1492. the compiler sees the expression <b>!string1</b>, it generates 
  1493. the function call<br>
  1494. <font size=2><br></font><font size=11><pre>
  1495. string1.operator!()<p>
  1496. </pre></font>
  1497. This function simply returns the result of testing if 
  1498. <b>length</b> is equal to zero.<br>
  1499. <spacer width=16 height=1>The lines<br>
  1500. <font size=2><br></font><font size=11><pre>
  1501. bool operator==( const String & ) const;  <p>
  1502.     // test s1 == s2<p>
  1503. bool operator<( const String & ) const;   <p>
  1504.     // test s1 < s2<p>
  1505. </pre></font>
  1506.  
  1507. </page>
  1508. <page>
  1509. declare the overloaded equality operator (defined at line 
  1510. 114) and the overloaded less than operator (defined at 
  1511. line 118) for the <b>String</b> class. These are all similar, so 
  1512. let us discuss one example, namely overloading the <b>==</b> 
  1513. operator. When the compiler sees the expression 
  1514. <b>string1</b> <b>== string2</b>, the compiler generates the function 
  1515. call<br>
  1516. <font size=2><br></font><font size=11><pre>
  1517. string1.operator==( string2 )<p>
  1518. </pre></font>
  1519. which returns <b>true</b> if <b>string1</b> is equal to <b>string2</b>. Each 
  1520. of these operators uses <b>strcmp</b> to compare the character 
  1521. strings in the <b>String</b> objects. Note that we use the 
  1522. function <b>strcmp</b> from the C Standard Library. Many 
  1523. C++ programmers advocate using some of the <br>
  1524.  
  1525. </page>
  1526. <page>
  1527. overloaded operator functions to implement others. So, 
  1528. the <b>!=</b>, <b>></b>, <b><=</b> and <b>>=</b> operators are implemented (lines 
  1529. 23 through 36) in terms of <b>operator==</b> and <b>operator<</b>. 
  1530. For example, overloaded function <b>operator>=</b> is 
  1531. implemented at line 35 in the header file as follows:<br>
  1532. <font size=2><br></font><font size=11><pre>
  1533. bool String::operator>=( const String &right ) const<p>
  1534.    { return !( *this < right ); }<p>
  1535. </pre></font>
  1536. The preceding <b>operator>=</b> definition uses the 
  1537. overloaded < operator to determine if one <b>String</b> object 
  1538. is greater than or equal to another. Note that the 
  1539. operator  <a href="^Engineer::c:s0p9"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>functions for <b>!=</b>, <b>></b>, <b><=</b> and <b>>=</b> are defined in 
  1540. the header file. The compiler <b>inlines</b> these definitions to 
  1541. eliminate the overhead of the extra function calls.<br>
  1542.  
  1543. </page>
  1544. <page>
  1545. Lines 38 and 39<br>
  1546. <font size=2><br></font><font size=11><pre>
  1547. char &operator[]( int );             <p>
  1548.     // subscript operator<p>
  1549. const char &operator[]( int ) const; <p>
  1550.     // subscript operator<p>
  1551. </pre></font>
  1552. declare two overloaded subscript operators (defined at 
  1553. lines 122 and 131)--one for non-<b>const Strings</b> and one 
  1554. for <b>const Strings</b>. When the compiler sees an 
  1555. expression like <b>string1[ 0 ]</b>, the compiler generates the 
  1556. call <b>string1.operator[]( 0 )</b> (using the appropriate 
  1557. version of <b>operator[]</b> based on whether or not the 
  1558. <b>String</b> is <b>const</b>). Function <b>operator[]</b> first uses <b>assert</b> 
  1559. to perform a range check on the  <a href="^Debug::c:s0p0"><img src="bckgrnds/icons/dbt_ico.gif" align=sidebar></a>subscript; if the 
  1560. subscript is out of range, the program will print an error <br>
  1561.  
  1562. </page>
  1563. <page>
  1564. message and terminate abnormally. If the subscript is in 
  1565. range, the non-<b>const</b> version of <b>operator[]</b> returns as a 
  1566. <b>char &</b> to the appropriate character of the <b>String</b> 
  1567. object; this <b>char &</b> may be used as an <i>lvalue</i> to modify 
  1568. the designated character of the <b>String</b> object. The <b>const</b> 
  1569. version of <b>operator[]</b> returns <b>const char &</b> to the 
  1570. appropriate character of the <b>String</b> object; this <b>char &</b> 
  1571. may be used as an <i>rvalue</i> to read the value of the 
  1572. character.<br>
  1573. <spacer width=16 height=1>Line 40<br>
  1574. <font size=2><br></font><font size=11><pre>
  1575. String &operator()( int, int ); // return a substring<p>
  1576. </pre></font>
  1577. declares the <i>overloaded function-call operator</i> (defined 
  1578. at line 141). In string classes, it is common to overload <br>
  1579.  
  1580. </page>
  1581. <page>
  1582. this operator to select a substring from a <b>String</b> object. 
  1583. The two integer parameters specify the start location 
  1584. and the length of the substring being selected from the 
  1585. <b>String</b>. If the start location is out of range or the 
  1586. substring length is negative, an error message is 
  1587. generated. By convention, if the substring length is 0, 
  1588. then the substring is selected all the way to the end of 
  1589. the <b>String</b> object. For example, suppose <b>string1</b> is a 
  1590. <b>String</b> object containing the character string 
  1591. <b>"AEIOU"</b>. When the compiler sees the expression 
  1592. <b>string1( 2, 2 )</b>, it generates the call 
  1593. <b>string1.operator()( 2, 2 )</b>. When this call executes, it 
  1594. produces a new dynamically allocated <b>String</b> object <br>
  1595.  
  1596. </page>
  1597. <page>
  1598. containing the string <b>"IO"</b> and returns a reference to 
  1599. this object. <br>
  1600. <spacer width=16 height=1>Overloading the function call operator <b>()</b> is powerful 
  1601. because functions can take arbitrarily long and complex 
  1602. parameter lists. So we can use this capability for many 
  1603. interesting purposes. One such use of the function call 
  1604. operator is an alternate array subscripting notation: 
  1605. Instead of using C's awkward double square bracket 
  1606. notation for double arrays such as in a<b>[ b ][ c ]</b>, some 
  1607. programmers prefer to overload the function call 
  1608. operator to enable the notation <b>a( b, c )</b>. The overloaded 
  1609. function call operator can only be a non-<b>static</b> member <br>
  1610.  
  1611. </page>
  1612. <page>
  1613. function. This operator is used only when the "function 
  1614. name" is an object of class <b>String</b>.<br>
  1615. <spacer width=16 height=1>Line 41<br>
  1616. <font size=2><br></font><font size=11><pre>
  1617. int getLength() const;      // return string length<p>
  1618. </pre></font>
  1619. declares a function that returns the length of the <b>String</b> 
  1620. object. Note that this function (defined at line 168) 
  1621. obtains the length by returning the value of the <b>private</b> 
  1622. data of class <b>String</b>.<br>
  1623. <spacer width=16 height=1>At this point, the reader should now step through the 
  1624. code in <b>main</b>, examine the output window, and check 
  1625. each use of an overloaded operator.<br>
  1626.  
  1627. </page>
  1628. </section>
  1629. <section type=Body name=Default title="8.11 Overloading ++ and --">
  1630. <page>
  1631. <font size=18 bold>8.11 Overloading ++ and --</font><hr>
  1632. The increment and decrement operators--
  1633. preincrement, postincrement, predecrement, and 
  1634. postdecrement--can all be overloaded. We will see how 
  1635. the compiler distinguishes between the prefix version 
  1636. and the postfix version of an increment or decrement 
  1637. operator.<br>
  1638. <spacer width=16 height=1>To overload the increment operator to allow both 
  1639. preincrement and postincrement usage, each 
  1640. overloaded operator function must have a distinct 
  1641. signature so the compiler will be able to determine 
  1642. which version of <b>++ </b>is intended. The prefix versions are <br>
  1643.  
  1644. </page>
  1645. <page>
  1646. overloaded exactly as any other prefix unary operator 
  1647. would be. <br>
  1648. <spacer width=16 height=1>Suppose, for example, that we want to add 1 to the day 
  1649. in <b>Date</b> object <b>d1</b>. When the compiler sees the 
  1650. preincrementing expression<br>
  1651. <font size=2><br></font><font size=11><pre>
  1652. ++d1<p>
  1653. </pre></font>
  1654. the compiler generates the member function call<br>
  1655. <font size=2><br></font><font size=11><pre>
  1656. d1.operator++()<p>
  1657. </pre></font>
  1658. whose prototype would be<br>
  1659. <font size=2><br></font><font size=11><pre>
  1660. Date &operator++();<p>
  1661. </pre></font>
  1662. If the preincrementing is implemented as a non-member 
  1663. function, when the compiler sees the expression<br>
  1664. <font size=2><br></font><font size=11><pre>
  1665. ++d1<p>
  1666. </pre></font>
  1667.  
  1668. </page>
  1669. <page>
  1670. the compiler generates the function call<br>
  1671. <font size=2><br></font><font size=11><pre>
  1672. operator++( d1 )<p>
  1673. </pre></font>
  1674. whose prototype would be declared in the <b>Date</b> class as <br>
  1675. <font size=2><br></font><font size=11><pre>
  1676. friend Date &operator++( Date & );<p>
  1677. </pre></font>
  1678. Overloading the postincrementing operator presents a 
  1679. bit of a challenge because the compiler must be able to 
  1680. distinguish between the signatures of the overloaded 
  1681. preincrement and postincrement operator functions. 
  1682. The convention that has been adopted in C++ is that 
  1683. when the compiler sees the postincrementing 
  1684. expression <br>
  1685. <font size=2><br></font><font size=11><pre>
  1686. d1++<p>
  1687. </pre></font>
  1688. it will generate the member-function call<br>
  1689.  
  1690. </page>
  1691. <page>
  1692. <font size=2><br></font><font size=11><pre>
  1693. d1.operator++( 0 )<p>
  1694. </pre></font>
  1695. whose prototype is <br>
  1696. <font size=2><br></font><font size=11><pre>
  1697. Date operator++( int )<p>
  1698. </pre></font>
  1699. The 0 is strictly a "dummy value" to make the argument 
  1700. list of <b>operator++</b> used for postincrementing 
  1701. distinguishable from the argument list of <b>operator++</b> 
  1702. used for preincrementing.<br>
  1703. <spacer width=16 height=1>If the postincrementing is implemented as a non-
  1704. member function, when the compiler sees the 
  1705. expression<br>
  1706. <font size=2><br></font><font size=11><pre>
  1707. d1++<p>
  1708. </pre></font>
  1709. the compiler generates the function call<br>
  1710. <font size=2><br></font><font size=11><pre>
  1711. operator++(d1, 0)<p>
  1712. </pre></font>
  1713.  
  1714. </page>
  1715. <page>
  1716. whose prototype would be<br>
  1717. <font size=2><br></font><font size=11><pre>
  1718. friend Date operator++( Date &, int );<p>
  1719. </pre></font>
  1720. Once again, the <b>0</b> argument is used by the compiler so 
  1721. the argument list of <b>operator++</b> used for 
  1722. postincrementing is distinguishable from the argument 
  1723. list for preincrementing.<br>
  1724. <spacer width=16 height=1>Everything stated in this section for overloading 
  1725. preincrement and postincrement operators applies to 
  1726. overloading predecrement and postdecrement 
  1727. operators. Next, we examine a <b>Date</b> class with 
  1728. overloaded preincrement and postincrement operators.<br>
  1729.  
  1730. </page>
  1731. <page>
  1732. <b>Select the true statement(s). </b><br>
  1733. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  1734. The ++ operator can be overloaded for both preincrementing and postincrementing.  <br>
  1735. <component type="checkbox" width=20 height=18 label="" name=""  correct="True.">
  1736. The -- operator can be overloaded for both predecrementing and postdecrementing. <br>
  1737. <component type="checkbox" width=20 height=18 label="" name=""  feedback="False. The signature for a postincrement member function takes an int as a parameter.">
  1738. The signature for a preincrement member function takes an int as a parameter.   <br>
  1739. <component type=button name=b label="Check Your Answer" width=125 height=24>
  1740.  
  1741. </page>
  1742. </section>
  1743. <section type=Body name=Default title="8.12 Case Study: A Date Class">
  1744. <page>
  1745. <font size=18 bold>8.12 Case Study: A Date Class</font><hr>
  1746. <a href="^Code::c:s0p3"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 8.6</a> illustrates a <b>Date</b> class. The class uses 
  1747. overloaded preincrement and postincrement operators 
  1748. to add 1 to the day in a <b>Date</b> object, while causing 
  1749. appropriate increments to the month and year if 
  1750. necessary.<br>
  1751. <spacer width=16 height=1><tt><b>Date</b></tt>'s <b>public</b> interface includes an overloaded 
  1752. stream-insertion operator, a default constructor, a 
  1753. <b>setDate</b> function, an overloaded preincrement operator, 
  1754. an overloaded postincrement operator, an overloaded 
  1755. addition assignment operator (<b>+=</b>), a function to test for <br>
  1756.  
  1757. </page>
  1758. <page>
  1759. leap years, and a function to determine if a day is the 
  1760. last day of the month.<br>
  1761. The driver program in <b>main</b> creates the date objects <b>d1</b> 
  1762. which is initialized by default to January 1, 1900; <b>d2</b> 
  1763. which is initialized to December 27, 1992; and <b>d3</b> 
  1764. which the program attempts to initialize to an invalid 
  1765. date. The <b>Date</b> constructor calls <b>setDate</b> to validate the 
  1766. month, day, and year specified. If the month is invalid, 
  1767. it is set to 1. An invalid year is set to 1900. An invalid 
  1768. day is set to 1.<br>
  1769. <spacer width=16 height=1>The driver program outputs each of the constructed 
  1770. <b>Date</b> objects using the overloaded stream-insertion 
  1771. operator. The overloaded operator <b>+=</b> is used to add 7 <br>
  1772.  
  1773. </page>
  1774. <page>
  1775. days to <b>d2</b>. Then the <b>setDate</b> function is used to set <b>d3</b> 
  1776. to February 28, 1992. Next, a new <b>Date</b> object, <b>d4</b>, is 
  1777. set to March 18, 1969. Then <b>d4</b> is incremented by 1 
  1778. with the overloaded preincrement operator. The date is 
  1779. printed before and after the preincrementing to confirm 
  1780. that it worked correctly. Finally, <b>d4</b> is incremented with 
  1781. the overloaded postincrement operator. The date is 
  1782. printed before and after the postincrementing to 
  1783. confirm that it worked correctly.<br>
  1784. <spacer width=16 height=1>Overloading the preincrementing operator is 
  1785. straightforward. The preincrementing operator calls 
  1786. <b>private</b> utility function <b>helpIncrement</b> to increment 
  1787. the date. This function deals with "wraparounds" or <br>
  1788.  
  1789. </page>
  1790. <page>
  1791. "carries" that occur when we increment the last day of 
  1792. the month. These carries require incrementing the 
  1793. month. If the month is already 12, then the year must 
  1794. also be incremented. Function <b>helpIncrement</b> uses 
  1795. functions <b>leapYear</b> and <b>endOfMonth</b> to increment the 
  1796. day correctly.<br>
  1797. <spacer width=16 height=1>The overloaded preincrement operator returns a 
  1798. reference to the current <b>Date</b> object (i.e., the one that 
  1799. was just incremented). This occurs because the current 
  1800. object, <b>*this</b>, is returned as a <b>Date &</b>. <br>
  1801. <spacer width=16 height=1>Overloading the postincrement operator is a bit trickier. 
  1802. To emulate the effect of the postincrement, we must 
  1803. return an unincremented copy of the <b>Date</b> object. On <br>
  1804.  
  1805. </page>
  1806. <page>
  1807. entry to <b>operator++</b>, we save the current object (<b>*this</b>) 
  1808. in <b>temp</b>. Next, we call <b>helpIncrement</b> to increment the 
  1809. current <b>Date</b> object. Then, we return the unincremented 
  1810. copy of the object previously stored in <b>temp</b>. Note that 
  1811. this function cannot return a reference to the local <b>Date</b> 
  1812. object <b>temp</b> because local variables are destroyed when 
  1813. the function in which they are declared is exited. Thus, 
  1814. declaring the return type to this function as <b>Date &</b> 
  1815. would return a reference to an object that no longer 
  1816. exists. Returning a reference to a local variable is a 
  1817. common error for which some compilers will issue a 
  1818. warning.<br>
  1819.  
  1820. </page>
  1821. </section>
  1822. <section type=Body name=Default title="8.13 Summary">
  1823. <page>
  1824. <font size=18 bold>8.13 Summary</font><hr>
  1825. <indent width=8 delay>*   Operator << is used for multiple purposes in C++--
  1826. as the stream-insertion operator and as the left-shift 
  1827. operator. This is an example of operator overloading. 
  1828. Similarly, >> is also overloaded; it is used both as the 
  1829. stream-extraction operator and as the right-shift operator. </indent>
  1830. <indent width=8 delay>*   C++ enables the programmer to overload most operators to be sensitive to the context in which they are 
  1831. used. The compiler generates the appropriate code 
  1832. based on the manner in which the operator is used. </indent>
  1833. <indent width=8 delay>*  Operator overloading contributes to C++'s extensi</indent>
  1834.  
  1835. </page>
  1836. <page>
  1837. <indent width=8 delay>*   bility.</indent>
  1838. <indent width=8 delay>*   To overload an operator, write a function definition; 
  1839. the function name must be the keyword <b>operator</b> followed by the symbol for the operator being overloaded. </indent>
  1840. <indent width=8 delay>*   To use an operator on class objects, that operator 
  1841. <i>must</i> be overloaded--with two exceptions. The assignment operator (<b>=</b>) may be used with two objects of the 
  1842. same class to perform a default memberwise copy without overloading. The address operator (<b>&</b>) may also be 
  1843. used with objects of any class without overloading; it 
  1844. returns the address of the object in memory. </indent>
  1845. <indent width=8 delay>*  Operator overloading provides the same concise 
  1846. expressions for user-defined types that C++ provides </indent>
  1847.  
  1848. </page>
  1849. <page>
  1850. <indent width=8 delay>*   with its rich collection of operators that work on built-
  1851. in types.</indent>
  1852. <indent width=8 delay>*   The precedence and associativity of an operator cannot be changed by overloading. </indent>
  1853. <indent width=8 delay>*   It is not possible to change the number of operands 
  1854. an operator takes: Overloaded unary operators remain 
  1855. as unary operators; overloaded binary operators remain 
  1856. as binary operators. C++'s only ternary operator, <b>?:</b>, 
  1857. cannot be overloaded.</indent>
  1858. <indent width=8 delay>*   It is not possible to create symbols for new operators; 
  1859. only existing operators may be overloaded. </indent>
  1860. <indent width=8 delay>*   The meaning of how an operator works on objects of 
  1861. built-in types cannot be changed by overloading. </indent>
  1862.  
  1863. </page>
  1864. <page>
  1865. <indent width=8 delay>*   When overloading <b>()</b>, <b>[]</b>, <b>-></b>, or any assignment operator, the operator overloading function must be declared 
  1866. as a class member. </indent>
  1867. <indent width=8 delay>*   Operator functions can be member functions or non-
  1868. member functions.</indent>
  1869. <indent width=8 delay>*   When an operator function is implemented as a member function, the leftmost operand must be a class 
  1870. object (or a reference to a class object) of the operator's 
  1871. class. </indent>
  1872. <indent width=8 delay>*   If the left operand must be an object of a different 
  1873. class, this operator function must be implemented as a 
  1874. non-member function.</indent>
  1875. <indent width=8 delay>*  Operator member functions are called only when the </indent>
  1876.  
  1877. </page>
  1878. <page>
  1879. <indent width=8 delay>*   left operand of a binary operator is specifically an 
  1880. object of that class, or when the single operand of a 
  1881. unary operator is an object of that class.</indent>
  1882. <indent width=8 delay>*   One might choose a non-member function to overload an operator in order to enable the operator to be 
  1883. commutative (i.e., given the proper overloaded operator 
  1884. definitions, the left argument of an operator can be an 
  1885. object of another data type). </indent>
  1886. <indent width=8 delay>*   A unary operator can be overloaded as a non-<b>static</b> 
  1887. member function with no arguments or as a non-member function with one argument; that argument must be 
  1888. either an object of a user-defined type or a reference to 
  1889. an object of a user-defined type.</indent>
  1890.  
  1891. </page>
  1892. <page>
  1893. <indent width=8 delay>*   A binary operator can be overloaded as a non-<b>static</b> 
  1894. member function with one argument, or as a non-member function with two arguments (one of those arguments must be either a class object or a reference to a 
  1895. class object).</indent>
  1896. <indent width=8 delay>*   The array subscript operator <b>[]</b> is not restricted for 
  1897. use only with arrays; it can be used to select elements 
  1898. from other kinds of ordered container classes such as 
  1899. linked lists, strings, dictionaries, and so on. Also, subscripts no longer have to be integers; characters or 
  1900. strings could be used, for example.</indent>
  1901. <indent width=8 delay>*  A copy constructor is used to initialize an object with 
  1902. another object of the same class. Copy constructors are </indent>
  1903.  
  1904. </page>
  1905. <page>
  1906. <indent width=8 delay>*   also invoked whenever a copy of an object is needed, 
  1907. such as in call-by-value, and when returning a value 
  1908. from a called function. In a copy constructor, the object 
  1909. being copied must be passed in by reference.</indent>
  1910. <indent width=8 delay>*   The compiler does not automatically know how to 
  1911. convert between user-defined types and built-in types--
  1912. the programmer must explicitly specify how such conversions are to occur. Such conversions can be performed with conversion constructors (i.e., single-
  1913. argument constructors) that simply turn objects of other 
  1914. types into objects of a particular class.</indent>
  1915. <indent width=8 delay>*  A conversion operator (or cast operator) can be used 
  1916. to convert an object of one class into an object of </indent>
  1917.  
  1918. </page>
  1919. <page>
  1920. <indent width=8 delay>*   another class or into an object of a built-in type. Such a 
  1921. conversion operator must be a non-<b>static</b> member function; this kind of conversion operator cannot be a 
  1922. <b>friend</b> function. </indent>
  1923. <indent width=8 delay>*   A conversion constructor is a single-argument constructor used to convert the argument into an object of 
  1924. the constructor's class. The compiler can call such a 
  1925. constructor implicitly.</indent>
  1926. <indent width=8 delay>*   The assignment operator is the most frequently overloaded operator. It is normally used to assign an object 
  1927. to another object of the same class, but through the use 
  1928. of conversion constructors it can also be used to assign 
  1929. between different classes. </indent>
  1930.  
  1931. </page>
  1932. <page>
  1933. <indent width=8 delay>*   If an overloaded assignment operator is not defined, 
  1934. assignment is still allowed, but it defaults to a memberwise copy of each data member. In some cases this is 
  1935. acceptable. For objects that contain pointers to dynamically allocated storage, memberwise copy results in two 
  1936. different objects pointing to the same dynamically allocated storage. When the destructor for either of these 
  1937. objects is called, the dynamically allocated storage is 
  1938. released. If the other object then refers to that storage, 
  1939. the result is undefined.</indent>
  1940. <indent width=8 delay>*  To overload the increment operator to allow both 
  1941. preincrement and postincrement usage, each overloaded operator function must have a distinct signature </indent>
  1942.  
  1943. </page>
  1944. <page>
  1945. <indent width=8 delay>*   so the compiler will be able to determine which version 
  1946. of <b>++</b> is intended. The prefix versions are overloaded 
  1947. exactly as any other prefix unary operator. Providing a 
  1948. unique signature to the postincrement operator function 
  1949. is achieved by providing a second argument--which 
  1950. must be of type <b>int</b>. Actually, the user does not supply a 
  1951. value for this special integer argument. It is there simply to help the compiler distinguish between prefix and 
  1952. postfix versions of increment and decrement operators.</indent>
  1953.  
  1954. </page>
  1955. </section>
  1956. <section type=Popup name=Debug title="Testing">
  1957. <page>
  1958. Returning a <b>char</b> 
  1959. reference from an 
  1960. overloaded subscript 
  1961. operator in a <b>String</b> 
  1962. class is dangerous. For 
  1963. example, the client 
  1964. could use this reference 
  1965. to insert a null (<b>'\\0'</b>) 
  1966. anywhere in the string. <br>
  1967. <br>
  1968.  
  1969. </page>
  1970. </section>
  1971. <section type=Popup name=Terminology title="Terminology">
  1972. <page>
  1973. <font size=14>
  1974. C<br>
  1975. cascaded assignments 
  1976.  
  1977. <a href="%s8p21"><img src=iicons/bullbib.gif></a>
  1978. <a href="%s10p9"><img src=iicons/bullbib.gif></a>
  1979. <br>
  1980. cast operator function 
  1981.  
  1982. <a href="%s9p2"><img src=iicons/bullbib.gif></a>
  1983. <br>
  1984. class <b>Array</b> 
  1985. <a href="%s8p3"><img src=iicons/bullbib.gif></a>
  1986. <br>
  1987. class <b>Date</b> 
  1988. <br>
  1989. class <b>HugeInt</b> 
  1990. <a href="^Exercises::c:s0p16"><img src=iicons/bullbib.gif></a>
  1991. <br>
  1992. class <b>string</b> 
  1993. <a href="%s10p0"><img src=iicons/bullbib.gif></a>
  1994. <br>
  1995. conversion between a 
  1996. built-in type and a class 
  1997.  
  1998. <a href="%s10p12"><img src=iicons/bullbib.gif></a>
  1999. <br>
  2000. conversion constructor 
  2001.  
  2002. <a href="%s9p1"><img src=iicons/bullbib.gif></a>
  2003. <a href="%s10p3"><img src=iicons/bullbib.gif></a>
  2004. <a href="%s10p11"><img src=iicons/bullbib.gif></a>
  2005. <br>
  2006. </font>
  2007.  
  2008. </page>
  2009. <page>
  2010. <font size=14>
  2011. conversion operator 
  2012. <a href="%s9p1"><img src=iicons/bullbib.gif></a>
  2013. <br>
  2014. copy constructor 
  2015. <a href="%s8p6"><img src=iicons/bullbib.gif></a>
  2016.  
  2017. <a href="%s8p16"><img src=iicons/bullbib.gif></a>
  2018. <a href="^Errors::c:s0p10"><img src=iicons/bullbib.gif></a>
  2019. <br>
  2020. D<br>
  2021. dangling pointer 
  2022. <a href="^Errors::c:s0p9"><img src=iicons/bullbib.gif></a>
  2023.  
  2024. <a href="%s10p7"><img src=iicons/bullbib.gif></a>
  2025. <br>
  2026. default memberwise 
  2027. copy 
  2028. <a href="%s8p16"><img src=iicons/bullbib.gif></a>
  2029. <a href="%s10p6"><img src=iicons/bullbib.gif></a>
  2030. <br>
  2031. F<br>
  2032. <b>friend</b> function 
  2033. <a href="%s2p4"><img src=iicons/bullbib.gif></a>
  2034. <a href="%s8p3"><img src=iicons/bullbib.gif></a>
  2035. <br>
  2036. function call operator () 
  2037.  
  2038. <a href="%s10p19"><img src=iicons/bullbib.gif></a>
  2039. <br>
  2040. I<br>
  2041. implicit conversion 
  2042. <a href="^Engineer::c:s0p7"><img src=iicons/bullbib.gif></a>
  2043. <br>
  2044. </font>
  2045.  
  2046. </page>
  2047. <page>
  2048. <font size=14>
  2049. M<br>
  2050. memory leak 
  2051. <a href="%s10p9"><img src=iicons/bullbib.gif></a>
  2052. <br>
  2053. O<br>
  2054. <b>operator</b> keyword 
  2055. <a href="%s2p2"><img src=iicons/bullbib.gif></a>
  2056. <br>
  2057. operator overloading 
  2058. <a href="%s1p0"><img src=iicons/bullbib.gif></a>
  2059. <br>
  2060. <b>operator!</b> member 
  2061. function 
  2062. <a href="%s6p1"><img src=iicons/bullbib.gif></a>
  2063. <br>
  2064. <b>operator()</b> 
  2065.  
  2066. <a href="%s10p17"><img src=iicons/bullbib.gif></a>
  2067. <a href="^Exercises::c:s0p12"><img src=iicons/bullbib.gif></a>
  2068. <br>
  2069. <b>operator+</b> 
  2070. <a href="%s2p2"><img src=iicons/bullbib.gif></a>
  2071. <br>
  2072. <b>operator++</b> 
  2073. <a href="%s11p2"><img src=iicons/bullbib.gif></a>
  2074.  
  2075. <a href="%s12p4"><img src=iicons/bullbib.gif></a>
  2076. <br>
  2077. <b>operator++( int )</b> 
  2078.  
  2079. <a href="%s11p3"><img src=iicons/bullbib.gif></a>
  2080. <br>
  2081. </font>
  2082.  
  2083. </page>
  2084. <page>
  2085. <font size=14>
  2086. <b>operator+=</b> 
  2087.  
  2088. <a href="%s10p10"><img src=iicons/bullbib.gif></a>
  2089. <br>
  2090. <b>operator<</b> 
  2091.  
  2092. <a href="%s10p13"><img src=iicons/bullbib.gif></a>
  2093. <a href="%s10p15"><img src=iicons/bullbib.gif></a>
  2094. <br>
  2095. <b>operator<<</b> 
  2096. <a href="%s5p5"><img src=iicons/bullbib.gif></a>
  2097. <a href="%s8p11"><img src=iicons/bullbib.gif></a>
  2098. <a href="%s10p2"><img src=iicons/bullbib.gif></a>
  2099.  
  2100.  
  2101. <a href="^Exercises::c:s0p22"><img src=iicons/bullbib.gif></a>
  2102. <br>
  2103. <b>operator<=</b> 
  2104. <br>
  2105. <b>operator=</b> 
  2106. <a href="%s8p19"><img src=iicons/bullbib.gif></a>
  2107.  
  2108. <a href="%s10p8"><img src=iicons/bullbib.gif></a>
  2109. <br>
  2110. <b>operator==</b> 
  2111. <a href="%s8p21"><img src=iicons/bullbib.gif></a>
  2112.  
  2113. <a href="%s8p23"><img src=iicons/bullbib.gif></a>
  2114. <a href="%s10p13"><img src=iicons/bullbib.gif></a>
  2115. <a href="%s10p15"><img src=iicons/bullbib.gif></a>
  2116. <br>
  2117. <b>operator></b> 
  2118. <br>
  2119. <b>operator>=</b> 
  2120. <a href="%s10p15"><img src=iicons/bullbib.gif></a>
  2121. <br>
  2122. </font>
  2123.  
  2124. </page>
  2125. <page>
  2126. <font size=14>
  2127. <b>operator>></b> 
  2128. <a href="%s5p1"><img src=iicons/bullbib.gif></a>
  2129. <a href="%s5p2"><img src=iicons/bullbib.gif></a>
  2130. <a href="%s5p3"><img src=iicons/bullbib.gif></a>
  2131.  
  2132. <a href="%s5p5"><img src=iicons/bullbib.gif></a>
  2133. <a href="%s8p12"><img src=iicons/bullbib.gif></a>
  2134. <a href="%s10p2"><img src=iicons/bullbib.gif></a>
  2135. <br>
  2136. <b>operator[]</b> 
  2137.  
  2138. <a href="%s10p16"><img src=iicons/bullbib.gif></a>
  2139. <br>
  2140. overloaded 
  2141. <a href="%s4p2"><img src=iicons/bullbib.gif></a>
  2142. <br>
  2143. overloaded <b>+=</b> 
  2144. concatenation operator 
  2145.  
  2146. <a href="^Perform::c:s0p2"><img src=iicons/bullbib.gif></a>
  2147. <br>
  2148. overloaded <b><</b> operator 
  2149.  
  2150. <a href="%s10p15"><img src=iicons/bullbib.gif></a>
  2151. <br>
  2152. overloaded addition 
  2153. assignment operator (<b>+=</b>) 
  2154.  
  2155. <a href="%s12p0"><img src=iicons/bullbib.gif></a>
  2156. <br>
  2157. </font>
  2158.  
  2159. </page>
  2160. <page>
  2161. <font size=14>
  2162. overloaded assignment 
  2163. operator (<b>=</b>) 
  2164. <a href="%s8p7"><img src=iicons/bullbib.gif></a>
  2165. <a href="%s10p4"><img src=iicons/bullbib.gif></a>
  2166. <br>
  2167. overloaded equality 
  2168. operator (<b>==</b>) 
  2169. <a href="%s8p8"><img src=iicons/bullbib.gif></a>
  2170. <a href="%s8p21"><img src=iicons/bullbib.gif></a>
  2171.  
  2172. <a href="%s10p14"><img src=iicons/bullbib.gif></a>
  2173. <br>
  2174. overloaded inequality 
  2175. operator (<b>!=</b>) 
  2176. <a href="%s8p6"><img src=iicons/bullbib.gif></a>
  2177. <a href="%s8p22"><img src=iicons/bullbib.gif></a>
  2178. <br>
  2179. overloaded operator <b>+=</b> 
  2180.  
  2181. <a href="%s12p1"><img src=iicons/bullbib.gif></a>
  2182. <br>
  2183. overloading 
  2184. <a href="%s1p1"><img src=iicons/bullbib.gif></a>
  2185. <br>
  2186. overloading binary 
  2187. operators 
  2188. <a href="%s7p0"><img src=iicons/bullbib.gif></a>
  2189. <br>
  2190. S<br>
  2191. </font>
  2192.  
  2193. </page>
  2194. <page>
  2195. <font size=14>
  2196. self-assignment 
  2197. <a href="%s8p19"><img src=iicons/bullbib.gif></a>
  2198.  
  2199. <a href="%s10p8"><img src=iicons/bullbib.gif></a>
  2200. <br>
  2201. single-argument 
  2202. constructor 
  2203. <a href="%s9p1"><img src=iicons/bullbib.gif></a>
  2204. <a href="%s10p3"><img src=iicons/bullbib.gif></a>
  2205. <br>
  2206. string 
  2207. <a href="%s10p1"><img src=iicons/bullbib.gif></a>
  2208. <br>
  2209. substring 
  2210. <a href="%s10p18"><img src=iicons/bullbib.gif></a>
  2211. <br>
  2212. U<br>
  2213. user-defined type 
  2214. <a href="%s9p1"><img src=iicons/bullbib.gif></a>
  2215. <br>
  2216. <br>
  2217. </font>
  2218.  
  2219. </page>
  2220. </section>
  2221. <section type=Popup name=Illustration title="Illustrations">
  2222. <page>
  2223. <a href="^Illustration::c:s0p1">Fig. 8.1</a>  Operators that can be overloaded.<br>
  2224. <a href="^Illustration::c:s0p2">Fig. 8.2</a>  Operators that cannot be overloaded.<br>
  2225. <a href="^Code::c:s0p0">Fig. 8.3</a>  User-defined stream-insertion and stream-extraction operators.<br>
  2226. <a href="^Code::c:s0p1">Fig. 8.4</a>  Demonstrating an <b>Array</b> class with overloaded operators.<br>
  2227. <a href="^Code::c:s0p2">Fig. 8.5</a>  Definition of a basic <b>String</b> class.<br>
  2228. <a href="^Code::c:s0p3">Fig. 8.6</a>  Class <b>Date</b> with overloaded increment operators.<br>
  2229. <a href="^Code::c:s0p4">Fig. 8.7</a>  Demonstrating class <b>Complex</b>.<br>
  2230. <a href="^Code::c:s0p5">Fig. 8.8</a>  A user-defined huge integer class.<br>
  2231. <br>
  2232.  
  2233. </page>
  2234. <page>
  2235. <font size=18><a href="~audio/Ch08/08fig001.au"><img src="bckgrnds/icons/audio.gif" align=sidebar></a>Figure 8.1 - Operators that can be overloaded.<img src="graphics/ch08/fig08001.gif" ></font><br>
  2236.  
  2237. </page>
  2238. <page>
  2239. <font size=18><a href="~audio/Ch08/08fig002.au"><img src="bckgrnds/icons/audio.gif" align=sidebar></a>Figure 8.2 - Operators that cannot be overloaded.<img src="graphics/ch08/fig08002.gif" ></font><br>
  2240.  
  2241. </page>
  2242. </section>
  2243. <section type=Popup name=Objective title="Objectives">
  2244. <page>
  2245. <indent width=8 delay>*   To understand how to redefine (overload) operators to work with new 
  2246. types.</indent>
  2247. <indent width=8 delay>*   To understand how to convert objects from one class to another class.</indent>
  2248. <indent width=8 delay>*   To learn when to, and when not to, overload operators.</indent>
  2249. <indent width=8 delay>*   To study several interesting classes that use overloaded operators.</indent>
  2250. <foreign  name="audio" url="~audio/Ch08/08obj.au">
  2251.  
  2252. </page>
  2253. <page>
  2254. <indent width=8 delay>*   To create Array, String, and Date classes.</indent>
  2255.  
  2256. </page>
  2257. </section>
  2258. <section type=Popup name=Practice title="Good Practices">
  2259. <page>
  2260. Avoid excessive or 
  2261. inconsistent use of 
  2262. operator overloading as 
  2263. this can make a 
  2264. program cryptic and 
  2265. difficult to read.<br>
  2266. <br>
  2267.  
  2268. </page>
  2269. <page>
  2270. Use operator 
  2271. overloading when it 
  2272. makes a program 
  2273. clearer than 
  2274. accomplishing the same 
  2275. operations with explicit 
  2276. function calls.<br>
  2277. <br>
  2278.  
  2279. </page>
  2280. <page>
  2281. Before writing C++ 
  2282. programs with 
  2283. overloaded operators, 
  2284. consult the manuals for 
  2285. your compiler to 
  2286. become aware of 
  2287. restrictions and 
  2288. requirements unique to 
  2289. particular operators.<br>
  2290. <br>
  2291.  
  2292. </page>
  2293. <page>
  2294. Overload operators to 
  2295. perform the same 
  2296. function or similar 
  2297. functions on class 
  2298. objects as the operators 
  2299. perform on objects of 
  2300. built-in types. Avoid 
  2301. non-intuitive uses of 
  2302. operators.<br>
  2303. <br>
  2304.  
  2305. </page>
  2306. <page>
  2307. To ensure consistency 
  2308. among related 
  2309. operators, use one to 
  2310. implement the others 
  2311. (i.e., use an overloaded 
  2312. <b>+ </b>operator to 
  2313. implement an 
  2314. overloaded <b>+=</b> 
  2315. operator). <br>
  2316. <br>
  2317.  
  2318. </page>
  2319. <page>
  2320. When overloading 
  2321. unary operators, it is 
  2322. preferable to make the 
  2323. operator functions class 
  2324. members instead of 
  2325. non-member <b>friend</b> 
  2326. functions. <b>friend</b> 
  2327. functions and <b>friend</b> 
  2328. classes should be 
  2329. avoided unless they are <br>
  2330.  
  2331. </page>
  2332. <page>
  2333. absolutely necessary. 
  2334. The use of <b>friends</b> 
  2335. violates the 
  2336. encapsulation of a 
  2337. class.<br>
  2338. <br>
  2339.  
  2340. </page>
  2341. </section>
  2342. <section type=Popup name=Perform title="Performance">
  2343. <page>
  2344. It is possible to 
  2345. overload an operator as 
  2346. a non-member, non-
  2347. <b>friend</b> function, but 
  2348. such a function needing 
  2349. access to a class's 
  2350. <b>private</b> or <b>protected</b> 
  2351. data would need to use 
  2352. set or get functions 
  2353. provided in that class's <br>
  2354.  
  2355. </page>
  2356. <page>
  2357. <b>public</b> interface. The 
  2358. overhead of calling 
  2359. these functions could 
  2360. cause poor 
  2361. performance, so these 
  2362. functions can be 
  2363. <b>inlined</b> to improve 
  2364. performance.<br>
  2365. <br>
  2366.  
  2367. </page>
  2368. <page>
  2369. Having the overloaded 
  2370. <b>+= </b>concatenation 
  2371. operator that takes a 
  2372. single argument of type 
  2373. <b>const char * </b>executes 
  2374. more efficiently than 
  2375. having to do the 
  2376. implicit conversion 
  2377. first, then the 
  2378. concatenation. Implicit <br>
  2379.  
  2380. </page>
  2381. <page>
  2382. conversions require less 
  2383. code and cause fewer 
  2384. errors.<br>
  2385. <br>
  2386.  
  2387. </page>
  2388. </section>
  2389. <section type=Popup name=Code title="Code Examples">
  2390. <page>
  2391. <font size=18>Figure 8.3  User-defined stream-insertion and stream-extraction operators.</font><br>
  2392. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2393. <param  name="file" value="code/ch08/fig08_03.txt">
  2394. </applet><br>
  2395. <br>
  2396. <foreign  name="copy2disk" url="!jcpy Source/fig08_03.jar">
  2397. <foreign  name="audio" url="~audio/Ch08/08fig003.au">
  2398. <foreign  name="execute" url="!jarexe Run/fig08_03.jar">
  2399. <br>
  2400.  
  2401. </page>
  2402. <page>
  2403. <font size=18>Figure 8.4  Demonstrating an <b>Array</b> class with overloaded operators.</font><br>
  2404. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2405. <param  name="file" value="code/ch08/fig08_04.txt">
  2406. </applet><br>
  2407. <br>
  2408. <foreign  name="copy2disk" url="!jcpy Source/fig08_04.jar">
  2409. <foreign  name="audio" url="~audio/Ch08/08fig004.au">
  2410. <foreign  name="execute" url="!jarexe Run/fig08_04.jar">
  2411. <br>
  2412.  
  2413. </page>
  2414. <page>
  2415. <font size=18>Figure 8.5  Definition of a basic <b>String</b> class.</font><br>
  2416. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2417. <param  name="file" value="code/ch08/fig08_05.txt">
  2418. </applet><br>
  2419. <br>
  2420. <foreign  name="copy2disk" url="!jcpy Source/fig08_05.jar">
  2421. <foreign  name="audio" url="~audio/Ch08/08fig005.au">
  2422. <foreign  name="execute" url="!jarexe Run/fig08_05.jar">
  2423. <br>
  2424.  
  2425. </page>
  2426. <page>
  2427. <font size=18>Figure 8.6  Class <b>Date</b> with overloaded increment operators.</font><br>
  2428. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2429. <param  name="file" value="code/ch08/fig08_06.txt">
  2430. </applet><br>
  2431. <br>
  2432. <foreign  name="copy2disk" url="!jcpy Source/fig08_06.jar">
  2433. <foreign  name="audio" url="~audio/Ch08/08fig006.au">
  2434. <foreign  name="execute" url="!jarexe Run/fig08_06.jar">
  2435. <br>
  2436.  
  2437. </page>
  2438. <page>
  2439. <font size=18>Figure 8.7  Demonstrating class <b>Complex</b>.</font><br>
  2440. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2441. <param  name="file" value="code/ch08/fig08_07.txt">
  2442. </applet><br>
  2443. <br>
  2444. <foreign  name="copy2disk" url="!jcpy Source/fig08_07.jar">
  2445. <foreign  name="execute" url="!jarexe Run/fig08_07.jar">
  2446. <br>
  2447.  
  2448. </page>
  2449. <page>
  2450. <font size=18>Figure 8.8  A user-defined huge integer class.</font><br>
  2451. <applet code=gsl.win.helper.TextBox width=580 height=300>
  2452. <param  name="file" value="code/ch08/fig08_08.txt">
  2453. </applet><br>
  2454. <br>
  2455. <foreign  name="copy2disk" url="!jcpy Source/fig08_08.jar">
  2456. <foreign  name="execute" url="!jarexe Run/fig08_08.jar">
  2457. <br>
  2458.  
  2459. </page>
  2460. </section>
  2461. <section type=Popup name=Exercises title="Exercises">
  2462. <page pagename="Exercise 8.1">
  2463. <b>Exercise 8.1</b><br>
  2464. Fill in the blanks in each of the following:<br>
  2465. a)  Suppose <b>a</b> and <b>b</b> are integer variables and we form the sum <b>a + b</b>. Now 
  2466. suppose <b>c</b> and <b>d</b> are floating-point variables and we form the sum <b>c + d</b>. The two 
  2467. <b>+ </b>operators here are clearly being used for different purposes. This is an example 
  2468. of ________.<br>
  2469. b)  The keyword ________ introduces an overloaded operator function 
  2470. definition.<br>
  2471. c)  To use operators on class objects, they must be overloaded with the exception 
  2472. of the operators ________ and ________.<br>
  2473. d)  The ________, ________ and ________ of an operator cannot be 
  2474. changed by overloading the operator.<br>
  2475. <foreign  name="answers" url="^Answers::c:s0p0">
  2476.  
  2477. </page>
  2478. <page pagename="Exercise 8.2">
  2479. <b>Exercise 8.2</b><br>
  2480. Explain the multiple meanings of the operators<b> <<</b> and <b>>></b> in C++.<br>
  2481. <foreign  name="answers" url="^Answers::c:s0p1">
  2482.  
  2483. </page>
  2484. <page pagename="Exercise 8.3">
  2485. <b>Exercise 8.3</b><br>
  2486. In what context might the name <b>operator/</b> be used in C++?<br>
  2487. <foreign  name="answers" url="^Answers::c:s0p2">
  2488. <br>
  2489.  
  2490. </page>
  2491. <page pagename="Exercise 8.4">
  2492. <b>Exercise 8.4</b><br>
  2493. (True/False) In C++, only existing operators can be overloaded.<br>
  2494. <foreign  name="answers" url="^Answers::c:s0p3">
  2495. <br>
  2496.  
  2497. </page>
  2498. <page pagename="Exercise 8.5">
  2499. <b>Exercise 8.5</b><br>
  2500. How does the precedence of an overloaded operator in C++ compare with the 
  2501. precedence of the original operator?<br>
  2502. <foreign  name="answers" url="^Answers::c:s0p4">
  2503.  
  2504. </page>
  2505. <page pagename="Exercise 8.6">
  2506. <b>Exercise 8.6</b><br>
  2507. Give as many examples as you can of operator overloading implicit in C++. 
  2508. Give a reasonable example of a situation in which you might want to overload 
  2509. an operator explicitly in C++.<br>
  2510. <br>
  2511. <br>
  2512.  
  2513. </page>
  2514. <page pagename="Exercise 8.7">
  2515. <b>Exercise 8.7</b><br>
  2516. The C++ operators that cannot be overloaded are ____, ____, ____, ____, 
  2517. and ____.<br>
  2518. <br>
  2519.  
  2520. </page>
  2521. <page pagename="Exercise 8.8">
  2522. <b>Exercise 8.8</b><br>
  2523. String concatenation requires two operands--the two strings that are to be 
  2524. concatenated. In the text we showed how to implement an overloaded 
  2525. concatenation operator that concatenates the second <b>String</b> object to the right of 
  2526. the first <b>String</b> object, thus modifying the first <b>String</b> object. In some 
  2527. applications, it is desirable to produce a concatenated <b>String</b> object without 
  2528. modifying the <b>String</b> arguments. Implement <b>operator+</b> to allow operations such 
  2529. as<br>
  2530. <font size=2><br></font><font size=11><pre>
  2531. string1 = string2 + string3;<p>
  2532. </pre></font>
  2533. <br>
  2534.  
  2535. </page>
  2536. <page pagename="Exercise 8.9">
  2537. <b>Exercise 8.9</b><br>
  2538. <i>(Ultimate operator overloading exercise) </i>To appreciate the care that should go 
  2539. into selecting operators for overloading, list each of C++'s overloadable 
  2540. operators and for each list a possible meaning (or several, if appropriate) for 
  2541. each of several classes you have studied in this course. We suggest you try:<br>
  2542. a)  Array<br>
  2543. b)  Stack<br>
  2544. c)  String<br>
  2545. After doing this, comment on which operators seem to have meaning for a wide 
  2546. variety of classes. Which operators seem to be of little value for overloading? 
  2547. Which operators seem ambiguous?<br>
  2548. <br>
  2549.  
  2550. </page>
  2551. <page pagename="Exercise 8.10">
  2552. <b>Exercise 8.10</b><br>
  2553. Now work the process described in the previous problem in reverse. List each of 
  2554. C++'s overloadable operators. For each, list what you feel is perhaps the 
  2555. "ultimate operation" the operator should be used to represent. If there are several 
  2556. excellent operations, list them all.<br>
  2557. <br>
  2558.  
  2559. </page>
  2560. <page pagename="Exercise 8.11">
  2561. <b>Exercise 8.11</b><br>
  2562. <i>(Project)</i> C++ is an evolving language, and new languages are always being 
  2563. developed. What additional operators would you recommend adding to C++ or 
  2564. to a future language like C++ that would support both procedural programming 
  2565. and object-oriented programming? Write a careful justification. You might 
  2566. consider sending your suggestions to the ANSI C++ Committee. <br>
  2567. <br>
  2568. <br>
  2569.  
  2570. </page>
  2571. <page pagename="Exercise 8.12">
  2572. <b>Exercise 8.12</b><br>
  2573. One nice example of overloading the function call operator <b>()</b> is to allow the 
  2574. more common form of double-array subscripting. Instead of saying<br>
  2575. <font size=2><br></font><font size=11><pre>
  2576. chessBoard[ row ][ column ]<p>
  2577. </pre></font>
  2578. for an array of objects, overload the function call operator to allow the alternate 
  2579. form <br>
  2580. <font size=2><br></font><font size=11><pre>
  2581. chessBoard( row, column )<p>
  2582. </pre></font>
  2583. <foreign  name="answers" url="^Answers::c:s0p5">
  2584.  
  2585. </page>
  2586. <page pagename="Exercise 8.13">
  2587. <b>Exercise 8.13</b><br>
  2588. Create a class <b>DoubleSubscriptedArray</b> that has similar features to class 
  2589. <b>Array</b> in <a href="^Code::c:s0p1"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 8.4</a>. At construction time, the class should be able to create an 
  2590. array of any number of rows and any number of columns. The class should 
  2591. supply <b>operator()</b> to perform double subscripting operations. For example, in a 
  2592. 3-by-5 <b>DoubleSubscriptedArray</b> called <b>a</b>, the user could write <b>a( 1, 3 )</b> to 
  2593. access the element at row <b>1</b> and column <b>3</b>. Remember that <b>operator()</b> can 
  2594. receive any number of arguments (see class <b>String</b> in Fig. 18.5 for an example 
  2595. of <tt><b>operator()</b></tt>). The underlying representation of the double-subscripted array 
  2596. should be a single-subscripted array of integers with <i>rows * columns</i> number of 
  2597. elements. Function <b>operator()</b> should perform the proper pointer arithmetic to 
  2598. access each element of the array. There should be two versions of <b>operator()</b>--<br>
  2599.  
  2600. </page>
  2601. <page pagename="Exercise 8.13">
  2602. one that returns <b>int &</b> so an element of a <b>DoubleSubscriptedArray </b>can be used 
  2603. as an <i>lvalue</i> and one that returns <b>const int &</b> so an element of a <b>const 
  2604. DoubleSubscriptedArray</b> can be used as an <i>rvalue</i>. The class should also 
  2605. provide the following operators: <b>==</b>, <b>!=</b>, <b>=</b>, <b><<</b> (for outputting the array in row 
  2606. and column format) and <b>>></b> (for inputting the entire array contents).<br>
  2607. <br>
  2608.  
  2609. </page>
  2610. <page pagename="Exercise 8.14">
  2611. <b>Exercise 8.14</b><br>
  2612. Overload the subscript operator to return the largest element of a collection, the 
  2613. second largest, the third largest, etc.<br>
  2614. <br>
  2615. <br>
  2616.  
  2617. </page>
  2618. <page pagename="Exercise 8.15">
  2619. <b>Exercise 8.15</b><br>
  2620. Consider class <b>Complex</b> shown in <a href="^Code::c:s0p4"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 8.7</a>. The class enables operations on so-
  2621. called <i>complex numbers</i>. These are numbers of the form <b>realPart + 
  2622. imaginaryPart *</b> <i>i</i> where <i>i</i> has the value:<img src="graphics/ch08/ex08015.gif" ><br>
  2623. a)  Modify the class to enable input and output of complex numbers through the 
  2624. overloaded <b>>></b> and <b><<</b> operators, respectively (you should remove the print 
  2625. function from the class).<br>
  2626. b)  Overload the multiplication operator to enable multiplication of two complex 
  2627. numbers as in algebra.<br>
  2628. c)  Overload the <b>==</b> and <b>!=</b> operators to allow comparisons of complex numbers.<br>
  2629. <foreign  name="answers" url="^Answers::c:s0p6">
  2630.  
  2631. </page>
  2632. <page pagename="Exercise 8.16">
  2633. <b>Exercise 8.16</b><br>
  2634. A machine with 32-bit integers can represent integers in the range of 
  2635. approximately 2 billion to +2 billion. This fixed-size restriction is rarely 
  2636. troublesome. But there are applications in which we would like to be able to use 
  2637. a much wider range of integers. This is what C++ was built to do, namely create 
  2638. powerful new data types. Consider class <b>HugeInt</b> of <a href="^Code::c:s0p5"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 8.8</a>. Study the class 
  2639. carefully, then<br>
  2640. a)  Describe precisely how it operates.<br>
  2641. b)  What restrictions does the class have?<br>
  2642. c)  Overload the <b>*</b> multiplication operator.<br>
  2643. d)  Overload the <b>/</b> division operator.<br>
  2644. e)  Overload all the relational and equality operators.<br>
  2645.  
  2646. </page>
  2647. <page pagename="Exercise 8.17">
  2648. <b>Exercise 8.17</b><br>
  2649. Create a class <b>RationalNumber</b> (fractions) with the following capabilities:<br>
  2650. a)  Create a constructor that prevents a 0 denominator in a fraction, reduces or 
  2651. simplifies fractions that are not in reduced form, and avoids negative 
  2652. denominators.<br>
  2653. b)  Overload the addition, subtraction, multiplication and division operators for 
  2654. this class.<br>
  2655. c)  Overload the relational and equality operators for this class.<br>
  2656. <br>
  2657. <br>
  2658.  
  2659. </page>
  2660. <page pagename="Exercise 8.18">
  2661. <b>Exercise 8.18</b><br>
  2662. Study the C string-handling library functions and implement each of the 
  2663. functions as part of the <b>String</b> class. Then, use these functions to perform text 
  2664. manipulations.<br>
  2665. <br>
  2666.  
  2667. </page>
  2668. <page pagename="Exercise 8.19">
  2669. <b>Exercise 8.19</b><br>
  2670. Develop class <b>Polynomial</b>. The internal representation of a <b>Polynomial</b> is an 
  2671. array of terms. Each term contains a coefficient and an exponent. The term<img src="graphics/ch08/ex08019.gif" ><br>
  2672. has a coefficient of 2 and an exponent of 4. Develop a full class containing 
  2673. proper constructor and destructor functions as well as <i>set</i> and <i>get</i> functions. The 
  2674. class should also provide the following overloaded operator capabilities:<br>
  2675. a)  Overload the addition operator (<b>+</b>) to add two <b>Polynomials</b>.<br>
  2676. b)  Overload the subtraction operator (<b>-</b>) to subtract two <b>Polynomials</b>.<br>
  2677. c)  Overload the assignment operator to assign one <b>Polynomial</b> to another.<br>
  2678. d)  Overload the multiplication operator (<b>*</b>) to multiply two <b>Polynomials</b>.<br>
  2679. <foreign  name="answers" url="^Answers::c:s0p7">
  2680.  
  2681. </page>
  2682. <page pagename="Exercise 8.19">
  2683. e)  Overload the addition assignment operator (<b>+=</b>), the subtraction assignment 
  2684. operator <p>
  2685. (<b>-=</b>), and the multiplication assignment operator (<b>*=</b>).<br>
  2686. <foreign  name="answers" url="^Answers::c:s0p7">
  2687.  
  2688. </page>
  2689. <page pagename="Exercise 8.20">
  2690. <b>Exercise 8.20</b><br>
  2691. The program of <a href="^Code::c:s0p0"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 8.3</a> contains the comment<br>
  2692. <font size=2><br></font><font size=11><pre>
  2693. // Overloaded stream-insertion operator (cannot be<p>
  2694. // a member function if we would like to invoke it with<p>
  2695. // cout << somePhoneNumber;)<p>
  2696. </pre></font>
  2697. Actually, it cannot be a member function of class <b>ostream</b>, but it can be a 
  2698. member function of class <b>PhoneNumber</b> if we were willing to invoke it in 
  2699. either of the following ways:<br>
  2700. <font size=2><br></font><font size=11><pre>
  2701. somePhoneNumber.operator<<( cout );<p>
  2702. </pre></font>
  2703. or<br>
  2704. <font size=2><br></font><font size=11><pre>
  2705. somePhoneNumber << cout;<p>
  2706. </pre></font>
  2707.  
  2708. </page>
  2709. <page pagename="Exercise 8.20">
  2710. Rewrite the program of <a href="^Code::c:s0p0"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 8.3</a> with the overloaded stream-insertion 
  2711. <tt><b>operator<<</b></tt> as a member function and try the two preceding statements in the 
  2712. program to prove that they work.<br>
  2713. <br>
  2714.  
  2715. </page>
  2716. </section>
  2717. <section type=Popup name=Engineer title="Engineering">
  2718. <page>
  2719. Operator overloading 
  2720. contributes to C++'s 
  2721. extensibility, one of the 
  2722. language's most 
  2723. appealing attributes.<br>
  2724. <br>
  2725.  
  2726. </page>
  2727. <page>
  2728. At least one argument 
  2729. of an operator function 
  2730. must be a class object 
  2731. or a reference to a class 
  2732. object. This prevents 
  2733. programmers from 
  2734. changing how operators 
  2735. work on built-in types.<br>
  2736. <br>
  2737.  
  2738. </page>
  2739. <page>
  2740. New input/output 
  2741. capabilities for user-
  2742. defined types can be 
  2743. added to C++ without 
  2744. modifying the 
  2745. declarations or <b>private</b> 
  2746. data members for either 
  2747. the <b>ostream</b> class or the 
  2748. <b>istream</b> class. This is 
  2749. another example of the <br>
  2750.  
  2751. </page>
  2752. <page>
  2753. extensibility of the C++ 
  2754. programming language. <br>
  2755. <br>
  2756.  
  2757. </page>
  2758. <page>
  2759. A constructor, a 
  2760. destructor, an 
  2761. overloaded assignment 
  2762. operator, and a copy 
  2763. constructor are usually 
  2764. provided as a group for 
  2765. any class that uses 
  2766. dynamically allocated 
  2767. memory.<br>
  2768. <br>
  2769.  
  2770. </page>
  2771. <page>
  2772. It is possible to prevent 
  2773. class objects from 
  2774. being copied; to do this, 
  2775. simply make both the 
  2776. overloaded assignment 
  2777. operator and the copy 
  2778. constructor <b>private</b>.<br>
  2779. <br>
  2780.  
  2781. </page>
  2782. <page>
  2783. It is possible to prevent 
  2784. one class object from 
  2785. being assigned to 
  2786. another. This is done by 
  2787. declaring the 
  2788. assignment operator as 
  2789. a <b>private</b> member of 
  2790. the class.<br>
  2791. <br>
  2792.  
  2793. </page>
  2794. <page>
  2795. When a conversion 
  2796. constructor is used to 
  2797. perform an implicit 
  2798. conversion, C++ can 
  2799. only apply a single 
  2800. implicit constructor call 
  2801. to try to match the 
  2802. needs of another 
  2803. overloaded operator. It 
  2804. is not possible to match <br>
  2805.  
  2806. </page>
  2807. <page>
  2808. an overloaded 
  2809. operator's needs by 
  2810. performing a series of 
  2811. implicit, user-defined 
  2812. conversions. <br>
  2813. <br>
  2814.  
  2815. </page>
  2816. <page>
  2817. By implementing 
  2818. member functions 
  2819. using previously 
  2820. defined member 
  2821. functions, the 
  2822. programmer reuses 
  2823. code to reduce the 
  2824. amount of code that 
  2825. must be written.<br>
  2826. <br>
  2827.  
  2828. </page>
  2829. </section>
  2830. <section type=Popup name=Errors title="Common Errors">
  2831. <page>
  2832. Attempting to overload 
  2833. a nonoverloadable 
  2834. operator is a syntax 
  2835. error.<br>
  2836. <br>
  2837.  
  2838. </page>
  2839. <page>
  2840. Attempting to create 
  2841. new operators via 
  2842. operator overloading is 
  2843. a syntax error.<br>
  2844. <br>
  2845.  
  2846. </page>
  2847. <page>
  2848. Attempting to change 
  2849. the "arity" of an 
  2850. operator via operator 
  2851. overloading is a syntax 
  2852. error.<br>
  2853. <br>
  2854.  
  2855. </page>
  2856. <page>
  2857. Assuming that 
  2858. overloading an operator 
  2859. such as <b>+ </b>automatically 
  2860. overloads related 
  2861. operators such as <b>+= </b>or 
  2862. that overloading <tt><i><b>==</b></i></tt> 
  2863. automatically overloads 
  2864. a related operator like 
  2865. <tt><i><b>!=</b></i></tt>. Operators can be 
  2866. overloaded only <br>
  2867.  
  2868. </page>
  2869. <page>
  2870. explicitly; there is no 
  2871. implicit overloading.<br>
  2872. <br>
  2873.  
  2874. </page>
  2875. <page>
  2876. Attempting to modify 
  2877. how an operator works 
  2878. with objects of built-in 
  2879. types is a syntax error.<br>
  2880. <br>
  2881.  
  2882. </page>
  2883. <page>
  2884. Note that the copy 
  2885. constructor must use 
  2886. call-by-reference not 
  2887. call-by-value. 
  2888. Otherwise, the copy 
  2889. constructor call results 
  2890. in infinite recursion (a 
  2891. fatal logic error) 
  2892. because, for call-by-
  2893. value, a copy of the <br>
  2894.  
  2895. </page>
  2896. <page>
  2897. object passed to the 
  2898. copy constructor must 
  2899. be made which results 
  2900. in the copy constructor 
  2901. being called 
  2902. recursively!<br>
  2903. <br>
  2904.  
  2905. </page>
  2906. <page>
  2907. If the copy constructor 
  2908. simply copied the 
  2909. pointer in the source 
  2910. object to the target 
  2911. object's pointer, then 
  2912. both objects would 
  2913. point to the same 
  2914. dynamically allocated 
  2915. storage. The first 
  2916. destructor to execute <br>
  2917.  
  2918. </page>
  2919. <page>
  2920. would then delete the 
  2921. dynamically allocated 
  2922. storage and the other 
  2923. object's <b>ptr</b> would then 
  2924. be undefined, a 
  2925. situation called a 
  2926. "<i>dangling pointer"</i> and 
  2927. likely to result in a 
  2928. serious run-time error. <br>
  2929. <br>
  2930.  
  2931. </page>
  2932. <page>
  2933. Not providing an 
  2934. overloaded assignment 
  2935. operator and a copy 
  2936. constructor for a class 
  2937. when objects of that 
  2938. class contain pointers to 
  2939. dynamically allocated 
  2940. storage is a logic error.<br>
  2941. <br>
  2942.  
  2943. </page>
  2944. </section>
  2945.  
  2946. <section type=Popup name=Portable title="Portability">
  2947. <page>
  2948. This chapter does not contain any Portability tips.
  2949. </page>
  2950. </section>
  2951. <section type=Popup name=AppletPopup title="Applet Examples">
  2952. <page>
  2953. This chapter does not contain any Applet Examples.
  2954. </page>
  2955. </section>
  2956. </chapter>
  2957. </html>
  2958. </html>
  2959.